Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in initialization of two dates in Javascript

Why do these two dates are differents :

var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10); // month (from 0-11)
date1.setDate(1); // day of the month (from 1-31)

var date2 = new Date(2012, 10, 1, 0, 0, 0, 0);

Result :

Date 1 : Sat Dec 01 2012 14:56:16 GMT+0100
Date 2 : Thu Nov 01 2012 00:00:00 GMT+0100

whereas these two dates are equals :

var date3 = new Date();
date3.setFullYear(2012); // year (four digits)
date3.setMonth(9); // month (from 0-11)
date3.setDate(1); // day of the month (from 1-31)

var date4 = new Date(2012, 9, 1, 0, 0, 0, 0);

Result :

Date 3 : Mon Oct 01 2012 14:56:16 GMT+0200
Date 4 : Mon Oct 01 2012 00:00:00 GMT+0200

Another question is why do date1.setMonth(10) gives a date in December (should be November).

like image 659
Jean-Charles Avatar asked Oct 31 '12 14:10

Jean-Charles


2 Answers

Finally got it. new Date() sets the date to the current date and time. In other words, October 31st (at the time of this writing).

When you then try to set the month to November, what's it to do? November only has 30 days... so it wraps it round to December.

If you change the order so that you set the day-of-month before the month, it works:

var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setDate(1); // day of the month (from 1-31)
date1.setMonth(10); // month (from 0-11)

Or as implied by jbabey's answer:

var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10, 1); // month (from 0-11) and day (1-31)

The documentation isn't terribly clear, but it's at least suggestive:

If a parameter you specify is outside of the expected range, setMonth attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1 (year + 1), and 3 will be used for month.

("Accordingly" is far from precise, but it means the implementation is at least arguably correct...)

like image 172
Jon Skeet Avatar answered Oct 16 '22 10:10

Jon Skeet


setMonth accepts a second parameter:

If you do not specify the dayValue parameter, the value returned from the getDate method is used.

When you set the month to 10 (November), it grabs the current day value (31) and sets that as the day. Since there are only 30 days in November, it rolls you over to December 1st.

like image 33
jbabey Avatar answered Oct 16 '22 09:10

jbabey