【问题标题】:How to convert mongodb timestamps to an actual date?如何将 mongodb 时间戳转换为实际日期?
【发布时间】:2020-03-31 09:07:23
【问题描述】:

我有这样的createdAt 属性:2020-03-30T12:44:20.221+00:00。现在,我想要30 march 2020 之类的东西。可能吗?我不需要时间和时区,只需要日期。谢谢。

【问题讨论】:

  • 你有没有尝试过?
  • 是的。 new Date("2020-03-30")
  • 您可以使用$toDatetimestamps转换成integer
  • "+00:00" 时区偏移量,相当于“Z”,即UTC。

标签: javascript mongodb date


【解决方案1】:

使用Date 构造函数:

var createdAt = "2020-03-30T12:44:20.221+00:00"
var date = new Date(createdAt)
console.log(date.getDate() +  " " + date.toLocaleString('default', { month: 'long' }) + " " + date.getFullYear())

// Or even more concise (Thanks @RobG)
console.log(date.toLocaleString('en-GB', {day:'numeric', month: 'long', year:'numeric'}))

【讨论】:

  • 如果您使用date.toLocaleString('en-GB', {day:'numeric', month: 'long', year:'numeric'}),您将一次性获得正确的格式。 :-)
【解决方案2】:

您说“我不需要时间和时区,只需要日期”,但是 2020-03-30T12:44:20.221+00:00 的偏移量为零,因此实际上是 UTC。根据时间戳和主机时区偏移中的时间,使用非 UTC 方法可能会产生一个日期,如果它在午夜的本地时区偏移范围内,则该日期是 UTC 日期的任一侧。

例如

let formatLocal = new Intl.DateTimeFormat('en-GB', {year: 'numeric', month:'long', day:'2-digit'});
let formatUTC   = new Intl.DateTimeFormat('en-GB', {year: 'numeric', month:'long', day:'2-digit', timeZone:'UTC'});

// Timestamps
['2020-03-30T12:44:20.221+00:00', // from OP
 '2020-03-30T00:04:00.000+00:00', // Just after midnight UTC
 '2020-03-29T23:54:00.000+00:00'  // Just before midnight UTC
].forEach(s => {
  let d = new Date(s);
  console.log(
   `${s}\nLocal: ${formatLocal.format(d)}\nUTC  : ${formatUTC.format(d)}`
  );
});

上面第二个或第三个示例的本地日期应从 UTC 日期偏移一天。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-29
    • 2019-05-09
    • 2021-10-23
    • 2018-12-25
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2019-09-15
    相关资源
    最近更新 更多