Javascript 现在日期 (UTC),格式为 yyyy-mm-dd HH:mm:ss

Jos*_*osh 2 javascript datetime date

我的大脑一定是彻底崩溃了,但我一生都无法弄清楚如何将 UTC 格式的当前日期和时间格式化为字符串。不管我做什么,我只是融入本地。

我有以下函数,它以正确的格式返回日期,但它始终是本地的。

let datenow = new Date;

console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"

function generateDatabaseDateTime(date) {
  const p = new Intl.DateTimeFormat('en', {
    year:'numeric',
    month:'2-digit',
    day:'2-digit',
    hour:'2-digit',
    minute:'2-digit',
    second:'2-digit',
    hour12: false
  }).formatToParts(date).reduce((acc, part) => {
    acc[part.type] = part.value;
      return acc;
  }, {});

  return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}
Run Code Online (Sandbox Code Playgroud)

有谁知道我错过了什么?

Viv*_*vek 7

我们应该使用内置toISOString函数将其转换为 ISO 日期格式,并使用字符串操作删除不需要的数据。

let datenow = new Date();

console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"

function generateDatabaseDateTime(date) {
  return date.toISOString().replace("T"," ").substring(0, 19);
}
Run Code Online (Sandbox Code Playgroud)

理想的解决方案应该是使用 momentjs 或 dayjs 库。