Last Updated: September 09, 2019
·
2.906K
· Tomás Prado

Go home Javascript Date, you are drunk

We had a little problem with some Javascript tests, today July 31.

We were doing this:

var date = new Date();
date.setYear(2013);   
date.setMonth(5);
date.setDate(13);

The variable date supposed to be "13 Jun 2013" but instead today was "13 Jul 2013".

Why?

Because in Javascript when you do setMonth without specifying the day, Javascript takes by default the current day. Today is 31. June 31 doesn't exists. To correct this overflow, Javascript jumps to the next month.

Thats why it was displaying "13 Jul 2013"

Go home Javascript date. You are drunk.

4 Responses
Add your response

Also months start with 0...which is um...stupid.

over 1 year ago ·

i myself prefer to use Moment.js, code became more readable and less buggy

over 1 year ago ·

JS Dates are awesome! XD

Some time ago I discovered the library date.js that seems good to avoid this kind of "unexpected behaviors": http://www.datejs.com

over 1 year ago ·

Yes, I use moment.js too to make things a little easier

over 1 year ago ·