Javascript new Date() give me the same result when executing getTime()

352 views Asked by At

To compage 2 date i'm doing a conversion from a string to the javascript Date object.

This is an exemple of the code i have:

 var date1 = new Date(dateArrray1[2], dateArrray1[1], dateArrray1[0], 0, 0, 0, 0);
 var date2 = new Date(dateArrray2[2], dateArrray2[1], dateArrray2[0], 0, 0, 0, 0);

My issu is on the fact that when i'm doing a validation on those 2 date object I got the same result on the getTime function for a certain date.

var date1 = new Date(2012, 01, 30, 12, 0, 0, 0).getTime()
var date2 = new Date(2012, 02, 01, 12, 0, 0, 0).getTime()

Normally the value of date1 dans date2 should be different. But surprise! The value of those 2 object are the same (actually the value is 1330621200000).

Do someone got the same issue as me?

2

There are 2 answers

2
SLaks On BEST ANSWER

Javascript dates use 0-based months.
If you pass an invalid date, such as February 30th, it will figure out what that date actually is.
Thus, February 30th of a leap year is the same as March 1st.

0
Alnitak On

The month field has the range 0 - 11, not 1 - 12

So in this case you've asked for the 30th of February and the 1st of March.

This year February has 29 days, so the 30th of Feb is (mathematically) the same as the 1st of March.