differenceInCalendarDays.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { millisecondsInDay } from "./constants.mjs";
  2. import { startOfDay } from "./startOfDay.mjs";
  3. import { getTimezoneOffsetInMilliseconds } from "./_lib/getTimezoneOffsetInMilliseconds.mjs";
  4. /**
  5. * @name differenceInCalendarDays
  6. * @category Day Helpers
  7. * @summary Get the number of calendar days between the given dates.
  8. *
  9. * @description
  10. * Get the number of calendar days between the given dates. This means that the times are removed
  11. * from the dates and then the difference in days is calculated.
  12. *
  13. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  14. *
  15. * @param dateLeft - The later date
  16. * @param dateRight - The earlier date
  17. *
  18. * @returns The number of calendar days
  19. *
  20. * @example
  21. * // How many calendar days are between
  22. * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
  23. * const result = differenceInCalendarDays(
  24. * new Date(2012, 6, 2, 0, 0),
  25. * new Date(2011, 6, 2, 23, 0)
  26. * )
  27. * //=> 366
  28. * // How many calendar days are between
  29. * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
  30. * const result = differenceInCalendarDays(
  31. * new Date(2011, 6, 3, 0, 1),
  32. * new Date(2011, 6, 2, 23, 59)
  33. * )
  34. * //=> 1
  35. */
  36. export function differenceInCalendarDays(dateLeft, dateRight) {
  37. const startOfDayLeft = startOfDay(dateLeft);
  38. const startOfDayRight = startOfDay(dateRight);
  39. const timestampLeft =
  40. +startOfDayLeft - getTimezoneOffsetInMilliseconds(startOfDayLeft);
  41. const timestampRight =
  42. +startOfDayRight - getTimezoneOffsetInMilliseconds(startOfDayRight);
  43. // Round the number of days to the nearest integer because the number of
  44. // milliseconds in a day is not constant (e.g. it's different in the week of
  45. // the daylight saving time clock shift).
  46. return Math.round((timestampLeft - timestampRight) / millisecondsInDay);
  47. }
  48. // Fallback for modularized imports:
  49. export default differenceInCalendarDays;