Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Date library repeating October

While trying to find out why I was having issues while working on a calendar, I ran into this issue. When setting the month to 8, the date is set to October, when the month is set to 9, the date is set to October. Code to test

var d = new Date();
document.write(d.getMonth());
d.setMonth(8);
document.write(d.getMonth());
d.setMonth(9);
document.write(d.getMonth());

output:
799

The current date is August 31st 2012, the month number should be 7, since the javascript months are 0 based.

Can someone explain this? I have been able to reproduce it on more than one computer.

like image 506
Paul Avatar asked Jul 13 '26 06:07

Paul


1 Answers

September only has 30 days - when you set the day to 31 (or create a date on the 31st of some month) and then change the month to one with fewer than 31 days JavaScript rolls the date over into the next month (in this case October). In other words, the date overflows.

> var d = new Date()
> d
Fri Aug 31 2012 22:53:50 GMT-0400 (EDT)
// Set the month to September, leaving the day set to the 31st
> d.setMonth(8) 
> d
Mon Oct 01 2012 22:53:50 GMT-0400 (EDT)

// Doing the same thing, changing the day first
> var d = new Date()
> d
Fri Aug 31 2012 22:53:50 GMT-0400 (EDT)
> d.setDate(30)
> d
Thu Aug 30 2012 22:53:50 GMT-0400 (EDT)
> d.setMonth(8)
Sun Sep 30 2012 22:53:50 GMT-0400 (EDT)

So the simple answer is, because the date for today is the 31st of August and the 31st of September is October 1st.

like image 176
Sean Vieira Avatar answered Jul 14 '26 19:07

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!