最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - new Date() returning invalid date unless * by 1? - Stack Overflow

programmeradmin0浏览0评论

I have a JSON object returning a unix timestamp of content piece's publish dates. This timestamp returns as an invalid date when using .toISOString() unless I multiply it by 1.

As an example

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

What is the reason behind this?

I have a JSON object returning a unix timestamp of content piece's publish dates. This timestamp returns as an invalid date when using .toISOString() unless I multiply it by 1.

As an example

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

What is the reason behind this?

Share Improve this question asked Mar 20, 2018 at 12:53 darcherdarcher 3,1343 gold badges27 silver badges32 bronze badges 3
  • 6 new Date( string ) will try to parse the string, while new Date( number ) will take unix timespan, timestamp * 1 will convert the string to a number so that works as you expect – Ovidiu Dolha Commented Mar 20, 2018 at 12:56
  • 2 You need to convert the string to a number for the timestamp new Date(+timestamp) – quirimmo Commented Mar 20, 2018 at 12:56
  • Please, consider reading the MDN Date documentation. Especially the parameters section. – Amin NAIRI Commented Mar 20, 2018 at 12:58
Add a ment  | 

1 Answer 1

Reset to default 6

The reason behind this is how new Date interprets its arguments.

Looking at the relevant prototypes we see:

new Date(value)

new Date(dateString)

Where value is a number and dateString a string.

This means the function acts different when passed a string and a number.

value is described by MDN as:

Integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).

And dateString as:

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-pliant RFC 2822 timestamps and also a version of ISO8601).

Since you pass it a string, it will use the second approach which is trying to parse the date.

Now, why does it work with * 1?

* 1 is converting the string to a number in an implicit manner.

You can also use parseInt to do this which is a bit more verbose:

new Date(parseInt('1584632700000', 10))
发布评论

评论列表(0)

  1. 暂无评论