Javascript date, is this my error or did I find a bug?

I have a section of simple Javascript in my application that has a link "Add Day", which adds 1 day to a date. It always works perfectly, except when the date gets to be 11/07/2010, and then the link suddenly will not work any longer. Its really wierd, because it only hangs up on the specific date of 11/07/2010.

How to reproduce error:

  1. Navigate to the page here
  2. On any date field, click "Today", or just set the date to today.
  3. Click "Add Day" until you get to 11/07/2010
  4. Now clicking "Add Day" does not work anymore!



The problem is that you're adding the 24 hours to the date to add one day; Daylight Savings Time has thwarted you because 24 hours after 00:00 on November 7th will be 23:00 (for the second time) on November 7th.


Others spotted what the problem is.

To fix it you can use the overloaded Date constructor that takes the year, month, and day:

var aDate = new Date(2010, 10, 07);
var aDatePlusOneDay = new Date(aDate.getFullYear(),
                               aDate.getDate() + 1, // HERE

Here's a more generic solution that can increment any date by a given millisecond amount, taking changes to daylight savings into account:

Date.addTicks = function(date, ticks) {
  var newDate = new Date(date.getTime() + ticks);
  var tzOffsetDelta = newDate.getTimezoneOffset() - date.getTimezoneOffset();
  return new Date(newDate.getTime() + tzOffsetDelta * 60000);

Adding a day to a Date object then is a matter of adding the number of milliseconds in one day:

Date.addTicks(new Date(2010, 10, 7), 86400000); // new Date(2010, 10, 8)



Daylight Savings Time. (In most places in the US) the time rolls back on the first Sunday of November. Your code is just adding an amount of milliseconds to the start of the day specified by the input box, and the returning the beginning of the resulting day: however because of DST, simply adding seconds and truncating the date this way will never progress the date.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.