differenceInCalendarDays.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { getTimezoneOffsetInMilliseconds } from "./_lib/getTimezoneOffsetInMilliseconds.js";
  2. import { normalizeDates } from "./_lib/normalizeDates.js";
  3. import { millisecondsInDay } from "./constants.js";
  4. import { startOfDay } from "./startOfDay.js";
  5. /**
  6. * The {@link differenceInCalendarDays} function options.
  7. */
  8. /**
  9. * @name differenceInCalendarDays
  10. * @category Day Helpers
  11. * @summary Get the number of calendar days between the given dates.
  12. *
  13. * @description
  14. * Get the number of calendar days between the given dates. This means that the times are removed
  15. * from the dates and then the difference in days is calculated.
  16. *
  17. * @param laterDate - The later date
  18. * @param earlierDate - The earlier date
  19. * @param options - The options object
  20. *
  21. * @returns The number of calendar days
  22. *
  23. * @example
  24. * // How many calendar days are between
  25. * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
  26. * const result = differenceInCalendarDays(
  27. * new Date(2012, 6, 2, 0, 0),
  28. * new Date(2011, 6, 2, 23, 0)
  29. * )
  30. * //=> 366
  31. * // How many calendar days are between
  32. * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
  33. * const result = differenceInCalendarDays(
  34. * new Date(2011, 6, 3, 0, 1),
  35. * new Date(2011, 6, 2, 23, 59)
  36. * )
  37. * //=> 1
  38. */
  39. export function differenceInCalendarDays(laterDate, earlierDate, options) {
  40. const [laterDate_, earlierDate_] = normalizeDates(
  41. options?.in,
  42. laterDate,
  43. earlierDate,
  44. );
  45. const laterStartOfDay = startOfDay(laterDate_);
  46. const earlierStartOfDay = startOfDay(earlierDate_);
  47. const laterTimestamp =
  48. +laterStartOfDay - getTimezoneOffsetInMilliseconds(laterStartOfDay);
  49. const earlierTimestamp =
  50. +earlierStartOfDay - getTimezoneOffsetInMilliseconds(earlierStartOfDay);
  51. // Round the number of days to the nearest integer because the number of
  52. // milliseconds in a day is not constant (e.g. it's different in the week of
  53. // the daylight saving time clock shift).
  54. return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInDay);
  55. }
  56. // Fallback for modularized imports:
  57. export default differenceInCalendarDays;