Javascript Date() function, abnormalities

101 views Asked by At

I recently encountered a problem with unreliable dates in javascript.

Here is an example you can test in your own browser console, to reproduce the problem.

s = new Date(0); s.setYear(2015); s
//Thu Dec 31 2015 18:00:00 GMT-0600 (Central Standard Time)

s.setMonth(5); s
//Wed Jul 01 2015 18:00:00 GMT-0500 (Central Daylight Time)

s.setMonth(6); s
//Wed Jul 01 2015 18:00:00 GMT-0500 (Central Daylight Time)

As you can see, set month of 5(june) is the same as 6 (july), both return july. This is resolved by instead using -- new Date() instead of new Date(0).

I would simply like to understand why that occurs. Reiterating, would like to understand WHY. Can anyone describe this behaviour?

https://wordpress.org/support/topic/front-end-submit-events-off-by-1month?replies=5#post-7059058

2

There are 2 answers

1
apsillers On BEST ANSWER
  • The date is initially December 31, 2015.
  • s.setMonth(5) sets the month to June (months are zero-indexed), so you're setting the date to June 31, 2015.
  • There is no such date (i.e., June has 30 days), so it rolls over to July 1, 2015.
  • Setting the month to July with s.setMonth(6) does nothing, because the date is already in July.

new Date() uses the current date (and today is not the 31st), so this 31-to-1 rollover does not occur.

1
JGV On

Reason for the issue is discussed here: javascript new Date(0) class shows 16 hours?

So, in your case, do not pass 0 in Date();

var s = new Date(); s.setYear(2015);

document.write(s);
document.write("<br/>");

s.setMonth(5);

document.write(s);
document.write("<br/>");


s.setMonth(6); 

document.write(s)