lc7viq
Last Updated: February 25, 2016
·
2.629K
· tomas2387

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

8379

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

over 1 year ago ·
8388

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

over 1 year ago ·
8400

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

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

over 1 year ago ·