differenceInWeeks.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { getRoundingMethod } from "./_lib/getRoundingMethod.js";
  2. import { differenceInDays } from "./differenceInDays.js";
  3. /**
  4. * The {@link differenceInWeeks} function options.
  5. */
  6. /**
  7. * @name differenceInWeeks
  8. * @category Week Helpers
  9. * @summary Get the number of full weeks between the given dates.
  10. *
  11. * @description
  12. * Get the number of full weeks between two dates. Fractional weeks are
  13. * truncated towards zero by default.
  14. *
  15. * One "full week" is the distance between a local time in one day to the same
  16. * local time 7 days earlier or later. A full week can sometimes be less than
  17. * or more than 7*24 hours if a daylight savings change happens between two dates.
  18. *
  19. * To ignore DST and only measure exact 7*24-hour periods, use this instead:
  20. * `Math.trunc(differenceInHours(dateLeft, dateRight)/(7*24))|0`.
  21. *
  22. * @param laterDate - The later date
  23. * @param earlierDate - The earlier date
  24. * @param options - An object with options
  25. *
  26. * @returns The number of full weeks
  27. *
  28. * @example
  29. * // How many full weeks are between 5 July 2014 and 20 July 2014?
  30. * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
  31. * //=> 2
  32. *
  33. * @example
  34. * // How many full weeks are between
  35. * // 1 March 2020 0:00 and 6 June 2020 0:00 ?
  36. * // Note: because local time is used, the
  37. * // result will always be 8 weeks (54 days),
  38. * // even if DST starts and the period has
  39. * // only 54*24-1 hours.
  40. * const result = differenceInWeeks(
  41. * new Date(2020, 5, 1),
  42. * new Date(2020, 2, 6)
  43. * )
  44. * //=> 8
  45. */
  46. export function differenceInWeeks(laterDate, earlierDate, options) {
  47. const diff = differenceInDays(laterDate, earlierDate, options) / 7;
  48. return getRoundingMethod(options?.roundingMethod)(diff);
  49. }
  50. // Fallback for modularized imports:
  51. export default differenceInWeeks;