Romain
Romain

Reputation: 573

Chrome javascript Date bug on 6 June 2013 exactly

I'm using the javascript Date object to convert field values into timestamp, the same piece of code works since several years, but today I had a strange behavior, with the date in the title.

It can be summarized by the following piece of code:

// 06 June 2013
DateTemp = new Date();
DateTemp.setFullYear( 2013 );
DateTemp.setMonth( 5 );
DateTemp.setDate( 6 );
DateTemp.setHours( 0 );
DateTemp.setMinutes( 0 );
DateTemp.setSeconds( 0 );
console.log( DateTemp.getMonth() ); // 5

DateTemp.setMonth( 6 );
console.log( DateTemp.getMonth() ); // 6

DateTemp.setMonth( 7 );
console.log( DateTemp.getMonth() ); // 7

I expect it to return: 5 6 7

But it outputs: 6 6 7

So if a user enters this date in the field, it stores the date one month later... Thank you in advance if someone can explain me where I totally messed up.

Have a nice day,

Upvotes: 3

Views: 640

Answers (1)

Sirko
Sirko

Reputation: 74036

Swap the lines, where you set the day with the one setting the month:

DateTemp = new Date();
DateTemp.setFullYear( 2013 );
DateTemp.setDate( 6 );
DateTemp.setMonth( 5 );
DateTemp.setHours( 0 );
DateTemp.setMinutes( 0 );
DateTemp.setSeconds( 0 );
console.log( DateTemp.getMonth() ); // 5

DateTemp.setMonth( 6 );
console.log( DateTemp.getMonth() ); // 6

DateTemp.setMonth( 7 );
console.log( DateTemp.getMonth() ); // 7

What is happening?

If you use the constructor new Date() a new Date object with the current date is created. So today this will be something like this:

Date {Fri May 31 2013 14:20:32 GMT+0200}

In your code you change, at first, the month to June. But there is no 31st of June, which is handled by JavaScript in such a way, that this is transformed to

Date {Mon Jul 01 2013 14:21:28 GMT+0200}

Afterwards your setting the day and all the other parts, which just works fine. But in the end it seems you are one month ahead.

So finally the solution is just to change the order of setting values in such a way, that this "overflow" does not happen or use the constructor with the respective arguments directly:

new Date( 2013, 5, 6 );

Upvotes: 8

Related Questions