Skip to content Skip to sidebar Skip to footer

Calculate Difference Between 2 Dates Considering Daylight Saving Time

Given a start date, and a number of 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_D

Solution 1:

To find the difference between two dates in whole days, create Date objects, subtract one from the other, then divide by the milliseconds in one day and round. The remainder will only be out by 1 hour for daylight saving so will round to the right value.

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

// Return Date given ISO date as yyyy-mm-ddfunctionparseISODate(ds) {
  var d = ds.split(/\D/);
  returnnewDate(d[0], --d[1], d[2]);
}

Get the difference in days:

functiondateDiff(d0, d1) {
  returnMath.round((d1 - d0)/8.64e7);
}

// 297console.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-25var d = newDate(2014, 9, 25);
d.setDate(d.getDate() + 2);

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

The built–in Date object takes account of daylight saving (thought there are bugs in some browsers).

Solution 2:

I prefer adding days this way:

var startDate = //someDate;var endDate = newDate(startDate.getFullYear(),
               startDate.getMonth(),
               startDate.getDate()+1);

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

This code add 1 day, if you want to add more, change the startDate.getDate()+1 for startDate.getDate()+NUMBER_OF_DAYS it works fine even if you are on the last day of month i.e. October 31th.

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

Post a Comment for "Calculate Difference Between 2 Dates Considering Daylight Saving Time"