Search code examples
moment-timezone

non-integral difference in days


I'm not asking why the following differenceInDays is wrong.

After figuring that out I kind of kicked myself.

But I wonder what's the right fix.

/**
 * differenceInDays - return the difference in days between 2 dates.
 *
 *   Since `moment.duration.asDays` can return a non-integral value
 *   (i.e. 36 hours == 1.5 days) each date is first adjusted to the
 *   start of day before the difference is determined.
 */
const differenceInDays = (date1, date2, timezone) => {
  const localStartOfDay1 = moment(date1)
    .tz(timezone)
    .startOf('day');
  const localStartOfDay2 = moment(date2)
    .tz(timezone)
    .startOf('day');
  return moment.duration(localStartOfDay2.diff(localStartOfDay1)).asDays();
};
  expect(differenceInDays('2020-03-08T17:00:00Z',
                          '2020-03-09T17:00:00Z',
                          'America/New_York')).toEqual(1);
    Expected value to equal:
      1
    Received:
      0.9583333333333334

Solution

  • The result might not be integral if DST transition or a leap adjustment happens between date1 and date2.

    One fix could be to just round the result.