Search code examples
javascriptdatetimeunix-timestamp

new Date() returning invalid date unless * by 1?


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?


Solution

  • 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-compliant 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))