4

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.

adiga
  • 34,372
  • 9
  • 61
  • 83
Kharlos Dominguez
  • 2,207
  • 8
  • 31
  • 43

3 Answers3

10

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I see now, thanks a lot. I'm coming from a .Net background and the DateTime object does not behave that way in there... I was suspecting I was doing something wrong... can't say I find this behavior very intuitive though, even though most things in programming are 0-based. – Kharlos Dominguez Mar 31 '11 at 09:34
  • It is even more unintuitive that the year and day parts do not seem to be 0-based... – Kharlos Dominguez Mar 31 '11 at 09:51
  • @Kharlos - Day numbers are 0 based too - 0 = Sunday - one of those things - more info here: [Why is January month 0 in Java Calendar ?](http://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar) – mplungjan Mar 31 '11 at 09:55
  • days are 1 based instead. what kind of policy is that? – morels Oct 21 '15 at 09:41
  • I do not understand your question – mplungjan Oct 21 '15 at 10:03
1

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

var myDate = new Date(2011, 1, 28); // 28th of february
Jonas G. Drange
  • 8,749
  • 2
  • 27
  • 38
1

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 !
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Deele
  • 3,728
  • 2
  • 33
  • 51