index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import startOfWeek from "../startOfWeek/index.js";
  2. import startOfWeekYear from "../startOfWeekYear/index.js";
  3. import toDate from "../toDate/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. var MILLISECONDS_IN_WEEK = 604800000;
  6. /**
  7. * @name getWeek
  8. * @category Week Helpers
  9. * @summary Get the local week index of the given date.
  10. *
  11. * @description
  12. * Get the local week index of the given date.
  13. * The exact calculation depends on the values of
  14. * `options.weekStartsOn` (which is the index of the first day of the week)
  15. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  16. * the first week of the week-numbering year)
  17. *
  18. * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
  19. *
  20. * @param {Date|Number} date - the given date
  21. * @param {Object} [options] - an object with options.
  22. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  23. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  24. * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
  25. * @returns {Number} the week
  26. * @throws {TypeError} 1 argument required
  27. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  28. * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
  29. *
  30. * @example
  31. * // Which week of the local week numbering year is 2 January 2005 with default options?
  32. * const result = getWeek(new Date(2005, 0, 2))
  33. * //=> 2
  34. *
  35. * // Which week of the local week numbering year is 2 January 2005,
  36. * // if Monday is the first day of the week,
  37. * // and the first week of the year always contains 4 January?
  38. * const result = getWeek(new Date(2005, 0, 2), {
  39. * weekStartsOn: 1,
  40. * firstWeekContainsDate: 4
  41. * })
  42. * //=> 53
  43. */
  44. export default function getWeek(dirtyDate, options) {
  45. requiredArgs(1, arguments);
  46. var date = toDate(dirtyDate);
  47. var diff = startOfWeek(date, options).getTime() - startOfWeekYear(date, options).getTime();
  48. // Round the number of days to the nearest integer
  49. // because the number of milliseconds in a week is not constant
  50. // (e.g. it's different in the week of the daylight saving time clock shift)
  51. return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
  52. }