differenceInWeeks.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { getRoundingMethod } from "./_lib/getRoundingMethod.mjs";
  2. import { differenceInDays } from "./differenceInDays.mjs";
  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. * @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).
  23. *
  24. * @param dateLeft - The later date
  25. * @param dateRight - The earlier date
  26. * @param options - An object with options
  27. *
  28. * @returns The number of full weeks
  29. *
  30. * @example
  31. * // How many full weeks are between 5 July 2014 and 20 July 2014?
  32. * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
  33. * //=> 2
  34. *
  35. * @example
  36. * // How many full weeks are between
  37. * // 1 March 2020 0:00 and 6 June 2020 0:00 ?
  38. * // Note: because local time is used, the
  39. * // result will always be 8 weeks (54 days),
  40. * // even if DST starts and the period has
  41. * // only 54*24-1 hours.
  42. * const result = differenceInWeeks(
  43. * new Date(2020, 5, 1),
  44. * new Date(2020, 2, 6)
  45. * )
  46. * //=> 8
  47. */
  48. export function differenceInWeeks(dateLeft, dateRight, options) {
  49. const diff = differenceInDays(dateLeft, dateRight) / 7;
  50. return getRoundingMethod(options?.roundingMethod)(diff);
  51. }
  52. // Fallback for modularized imports:
  53. export default differenceInWeeks;