index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import differenceInDays from "../differenceInDays/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. import { getRoundingMethod } from "../_lib/roundingMethods/index.js";
  4. /**
  5. * @name differenceInWeeks
  6. * @category Week Helpers
  7. * @summary Get the number of full weeks between the given dates.
  8. *
  9. * @description
  10. * Get the number of full weeks between two dates. Fractional weeks are
  11. * truncated towards zero by default.
  12. *
  13. * One "full week" is the distance between a local time in one day to the same
  14. * local time 7 days earlier or later. A full week can sometimes be less than
  15. * or more than 7*24 hours if a daylight savings change happens between two dates.
  16. *
  17. * To ignore DST and only measure exact 7*24-hour periods, use this instead:
  18. * `Math.floor(differenceInHours(dateLeft, dateRight)/(7*24))|0`.
  19. *
  20. *
  21. * @param {Date|Number} dateLeft - the later date
  22. * @param {Date|Number} dateRight - the earlier date
  23. * @param {Object} [options] - an object with options.
  24. * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`)
  25. * @returns {Number} the number of full weeks
  26. * @throws {TypeError} 2 arguments required
  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. * // How many full weeks are between
  34. * // 1 March 2020 0:00 and 6 June 2020 0:00 ?
  35. * // Note: because local time is used, the
  36. * // result will always be 8 weeks (54 days),
  37. * // even if DST starts and the period has
  38. * // only 54*24-1 hours.
  39. * const result = differenceInWeeks(
  40. * new Date(2020, 5, 1),
  41. * new Date(2020, 2, 6)
  42. * )
  43. * //=> 8
  44. */
  45. export default function differenceInWeeks(dateLeft, dateRight, options) {
  46. requiredArgs(2, arguments);
  47. var diff = differenceInDays(dateLeft, dateRight) / 7;
  48. return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff);
  49. }