0

I have a task to get days difference between 2 dates. My solution is like here https://stackoverflow.com/a/543152/3917754 just I use Math.ceil instead of Math.round - cause 1 day and something is more than 1 day.

It was fine until I got dates between DST change. For example:

In my timezone DST change was on 30 Oct.

So when I'm trying to find days diff between dates 20 Oct and 10 Nov in result I get 23 instead of 22.

There are solution how to identify DST date but is it good solution to add/substract 1 day if date is/isn't dst?

function datediff(toDate, fromDate) {        
    const millisecondsPerDay = 1000 * 60 * 60 * 24; // milliseconds in day
    fromDate.setHours(0, 0, 0, 0);                // Start just after midnight
    toDate.setHours(23, 59, 59, 999);             // End just before midnight
    const millisBetween = toDate.getTime() - fromDate.getTime();
    var days = Math.ceil(millisBetween / millisecondsPerDay);
    return days;
}

var startDate = new Date('2022-10-20');
var endDate = new Date('2022-11-10');

console.log('From date: ', startDate);
console.log('To date: ', endDate);

console.log(datediff(endDate, startDate));
demo
  • 6,038
  • 19
  • 75
  • 149
  • The answer depends. If your inputs are always whole dates, you can do all math in UTC and just add 1 day to avoid rounding. You don't even need to set any hours. But if your inputs are anything that a `Date` object can represent (any point in time to the millisecond), then you have to ask yourself exactly what kind of answer you want. Do you want the number of days with respect to local time? or with respect to UTC? or some other time zone? Or do you want the number of 24-hour intervals? (Keep in mind that the `Date` object is actually a *timestamp*, not a date.) – Matt Johnson-Pint Nov 07 '22 at 21:58

0 Answers0