【问题标题】:new Date() returning invalid date unless * by 1?new Date() 返回无效日期,除非 * 为 1?
【发布时间】:2018-03-20 12:53:48
【问题描述】:

我有一个 JSON 对象返回内容块发布日期的 unix 时间戳。使用.toISOString() 时,此时间戳返回为无效日期,除非我将其乘以 1。

举个例子

let timestamp = item[index].date; // returns string of "1584632700000"
let invalidDate = new Date(timestamp).toISOString(); // returns invalid Date
let validDate = new Date(timestamp * 1).toISOString(); // returns valid (and correct) Date

这背后的原因是什么?

【问题讨论】:

  • new Date( string ) 将尝试解析字符串,而 new Date( number ) 将占用 unix 时间跨度,timestamp * 1 会将字符串转换为数字,以便按预期工作
  • 您需要将字符串转换为时间戳new Date(+timestamp)的数字
  • 请考虑阅读MDN Date documentation。尤其是参数部分。

标签: javascript datetime unix-timestamp


【解决方案1】:

这背后的原因是 new Date 如何解释它的论点。

查看我们看到的相关原型:

新日期(值)

新日期(日期字符串)

其中value 是一个数字,dateString 是一个字符串。

这意味着函数在传递字符串和数字时的行为不同。

value 被 MDN 描述为:

整数值,表示自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数,忽略闰秒(Unix Epoch;但请考虑大多数 Unix 时间戳函数以秒为单位)。

dateString 为:

代表日期的字符串值。该字符串应采用 Date.parse() 方法可识别的格式(符合 IETF 的 RFC 2822 时间戳,也是 ISO8601 的一个版本)。

由于您将字符串传递给它,它会使用尝试解析日期的 second 方法。

现在,为什么它可以与 * 1 一起使用?

* 1 正在以隐式方式将字符串转换为数字。

您也可以使用 parseInt 来执行此操作,这有点冗长:

new Date(parseInt('1584632700000', 10))

【讨论】:

  • 谢谢,这让我找到了正确的方向,如果它是一个空字符串,parseInit() 也将返回 NaN 而不是 0。非常感谢!
猜你喜欢
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 2019-07-12
  • 2019-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多