0x777C
0x777C

Reputation: 1047

Two identical dates in different formats give different epoch times

The following statement:

(new Date("1993-09-01")).getTime() == (new Date(1993,9,1)).getTime()  

Seems to evaluate to false across both Node, Firefox and Chromium. Why does this happen?

Upvotes: 1

Views: 55

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272066

Two things:

  • For the long constructor, the month is 0-based. so new Date(1993, 9, 1) is not September but October 1 1993 local time
  • For the one argument constructor, when the string is passed in yyyy-mm-dd format, the engine could assume that the timezone is UTC or local depending on the specs being followed (ref). So new Date("1993-09-01").getTime() == new Date(1993, 8, 1) could still return false if the engine is following ES5 specs:

var d1 = new Date("1993-09-01");
var d2 = new Date(1993, 8, 1);
console.log(d1.toISOString());
console.log(d2.toISOString());

Upvotes: 1

wentjun
wentjun

Reputation: 42516

This is because the index for month in the JavaScript Date object starts from 0 (I.E. January is 0, February is 1, so on and so for).

For the statement on the right, new Date(1993,9,1) will result in 'Fri Oct 01 1993 00:00:00 GMT+0800 (Singapore Standard Time)' if when I try to console.log() it.

Try running the below code snippet:

const date1 = new Date(1993,9,1);
const date2 = new Date('1993-09-01');

console.log(date1);
console.log(date2);

According to the JavaScript Date object documentation, there are multiple ways of instantiating the Date Object. On your question, you have already used 2 of the formats mentioned on the documentation:

1) new Date(dateString) Some accepted formats for dateString include 'December 17, 1995 03:24:00', '1995-12-17T03:24:00', and '1993-09-01'.

2) new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

Do note that for the second argument monthIndex, the documentation stated that months are 0-based, meaning we have to start counting from 0.

Note: The argument monthIndex is 0-based. This means that January = 0 and December = 11.

Therefore, new Date(1993, 9, 1) would mean refer to 1st of October, 1993. You should be using new Date(1993, 8, 1) instead.


Even then, after making the above changes, the below snippet would print false. Why is this happening?

console.log((new Date('1993-09-01')).getTime() === (new Date(1993,8,1)).getTime())  

Once again, we refer to this section in the documentation:

If at least two arguments are supplied, missing arguments are either set to 1 (if the day is missing) or 0 for all others.

This means that in the case of new Date(1993,8,1), the remaining optional arguments (hours, minutes, seconds, and milliseconds) are set as 0. Hence, new Date(1993,8,1) is equivalent to writing new Date(1993,8,1,0,0,0,0)

Upvotes: 2

Related Questions