index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import differenceInDays from "../differenceInDays/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name differenceInWeeks
  5. * @category Week Helpers
  6. * @summary Get the number of full weeks between the given dates.
  7. *
  8. * @description
  9. * Get the number of full weeks between two dates. Fractional weeks are
  10. * truncated towards zero.
  11. *
  12. * One "full week" is the distance between a local time in one day to the same
  13. * local time 7 days earlier or later. A full week can sometimes be less than
  14. * or more than 7*24 hours if a daylight savings change happens between two dates.
  15. *
  16. * To ignore DST and only measure exact 7*24-hour periods, use this instead:
  17. * `Math.floor(differenceInHours(dateLeft, dateRight)/(7*24))|0`.
  18. *
  19. *
  20. * ### v2.0.0 breaking changes:
  21. *
  22. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  23. *
  24. * @param {Date|Number} dateLeft - the later date
  25. * @param {Date|Number} dateRight - the earlier date
  26. * @returns {Number} the number of full weeks
  27. * @throws {TypeError} 2 arguments required
  28. *
  29. * @example
  30. * // How many full weeks are between 5 July 2014 and 20 July 2014?
  31. * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
  32. * //=> 2
  33. *
  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 default function differenceInWeeks(dirtyDateLeft, dirtyDateRight) {
  47. requiredArgs(2, arguments);
  48. var diff = differenceInDays(dirtyDateLeft, dirtyDateRight) / 7;
  49. return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
  50. }