Kharlos Dominguez
Kharlos Dominguez

Reputation: 2277

JavaScript setDate returning wrong dates

I'm getting a date from a string, parsing it to get the day, month and year constituants and use these to instance a Date object.

What I am trying to achieve is to increment the date by one day. It all works fine except that the setDate method insists on returning me invalid dates sometimes...

For example, if I add 1 day to the 28th February 2011, it will return me 29th February 2011... a date which actually doesn't exist.

Is that a bug/limitation of the JavaScript's native Date/Time API, or am I just doing something wrong? I find it hard to believe that it behaves that way without checking the validity of the date.

var myDate = new Date(2011, 2, 28);
console.log(myDate.toString());

myDate.setDate(myDate.getDate() + 1);
console.log(myDate.toString()); // 29 February 2011 !

Thanks.

Upvotes: 4

Views: 9120

Answers (3)

Deele
Deele

Reputation: 3682

You forgot, that it counts months from 0. var myDate = new Date(2011, 2, 28); is actually Mon Mar 28 2011 00:00:00 GMT+0300 (FLE Daylight Time) {}

Try

 var myDate = new Date(2011, 1, 28);
 alert(myDate);
 myDate.setDate(myDate.getDate() + 1);
 alert(myDate); // 1 Mar 2011 !

Upvotes: 1

mplungjan
mplungjan

Reputation: 178411

You are not in February - month #2 is MARCH

JS months are 0 based

 var myDate = new Date(2011, 1, 28); // 28th of Feb
 alert(myDate);
 myDate.setDate(myDate.getDate() + 1);
 alert(myDate); // 1st of March 2011 !

PS: Where you MAY have some issues are across the daylight savings time if you are creating dates using var d = new Date() and don't normalise on hours by doing d.setHours(0,0,0,0) afterwards

Upvotes: 10

Jonas G. Drange
Jonas G. Drange

Reputation: 8845

No, you are using March, aren't you? 29th of March exists.

var myDate = new Date(2011, 1, 28); // 28th of february

Upvotes: 1

Related Questions