Calculate the difference between 2 dates including daylight saving time

Given a start date and several days, I need to display the end date = start date + number of days.

So, I did something like this:

var endDate=new Date(startDate.getTime()+ONE_DAY);


Everything works fine, except for one less day during October 25th and 26th.


2014-01-01 + 2 days = 2014-01-03

2014-10-25 + 2 days = 2014-10-26 (here is the case I need to treat).


This difference arises because the watch goes back 1 hour. It practically 2014-10-27 00:00:00

becomes 2014-10-26 23:00:00


A simple solution would be to calculate this at a different hour (example 3 AM). But I just want to show a note when this happens.

For example, if the user enters 2014-10-25

, I show the popup say [something].

Now here's the real problem ... I can't seem to find an algorithm that says when the clock returns to year X.

Example ... in 2014, the day is October 26. In 2016 - October 30 ( ). What for? This date looks random, but I don't think it is. So ... when does the clock go backward / forward?

EDIT: All answers / comments are helpful on how to fix the problem. But ... I've already passed this stage. Now I only have an itch about "how do days on earth happen when the clock changes?"


source to share

2 answers

To find the difference between two dates for an entire day, create Date objects, subtract one from the other, and then divide them into milliseconds for one day and a circle. The rest will only be available for 1 hour for Daylight Saving Time, so it will be rounded to the correct value.

You may also need a little function to convert strings to Dates:

// Return Date given ISO date as yyyy-mm-dd
function parseISODate(ds) {
  var d = ds.split(/\D/);
  return new Date(d[0], --d[1], d[2]);


Get the difference in days:

function dateDiff(d0, d1) {
  return Math.round((d1 - d0)/8.64e7);

// 297
console.log(dateDiff(parseISODate('2014-01-01'), parseISODate('2014-10-25')));


If you want to add days to a date, do something like:

// Add 2 days to 2014-10-25
var d = new Date(2014, 9, 25);
d.setDate(d.getDate() + 2);

console.log(d);   // 2014-10-27


The built-in Date object takes daylight saving time into account (believed to have bugs in some browsers).



I prefer to add days like this:

    var startDate = //someDate;

    var endDate = new Date(startDate.getFullYear(),


This way, you don't have to worry about the days on the calendar.

This code add 1 day, if you want to add more change startDate.getDate()+1

to startDate.getDate()+NUMBER_OF_DAYS

, it works great even if you are on the last day of the month, that is October 31st.

But maybe you can use @ RobG's solution which is more elegant than mine.



All Articles