lc7viq
Last Updated: February 25, 2016
·
2.563K
· tomas2387
40276387b66caf2bbf4e1b764da1b807

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.

Say Thanks
Respond

4 Responses
Add your response

8379
Screen shot 2012 08 27 at 9.12.28 pm

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

over 1 year ago ·
8388
8da6536c9ddc7a16a9235dfea6c3c09b

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

over 1 year ago ·
8400
Seriousmeh square

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 ·
8440
3f23a52c7bc87296e96b5a05547da0e0

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

over 1 year ago ·