Source: differenceInCalendarISOWeeks/index.js

  1. import getTimezoneOffsetInMilliseconds from '../_lib/getTimezoneOffsetInMilliseconds/index'
  2. import startOfISOWeek from '../startOfISOWeek/index'
  3. import requiredArgs from '../_lib/requiredArgs/index'
  4. var MILLISECONDS_IN_WEEK = 604800000
  5. /**
  6. * @name differenceInCalendarISOWeeks
  7. * @category ISO Week Helpers
  8. * @summary Get the number of calendar ISO weeks between the given dates.
  9. *
  10. * @description
  11. * Get the number of calendar ISO weeks between the given dates.
  12. *
  13. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  14. *
  15. * ### v2.0.0 breaking changes:
  16. *
  17. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  18. *
  19. * @param {Date|Number} dateLeft - the later date
  20. * @param {Date|Number} dateRight - the earlier date
  21. * @returns {Number} the number of calendar ISO weeks
  22. * @throws {TypeError} 2 arguments required
  23. *
  24. * @example
  25. * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?
  26. * var result = differenceInCalendarISOWeeks(
  27. * new Date(2014, 6, 21),
  28. * new Date(2014, 6, 6)
  29. * )
  30. * //=> 3
  31. */
  32. export default function differenceInCalendarISOWeeks(
  33. dirtyDateLeft,
  34. dirtyDateRight
  35. ) {
  36. requiredArgs(2, arguments)
  37. var startOfISOWeekLeft = startOfISOWeek(dirtyDateLeft)
  38. var startOfISOWeekRight = startOfISOWeek(dirtyDateRight)
  39. var timestampLeft =
  40. startOfISOWeekLeft.getTime() -
  41. getTimezoneOffsetInMilliseconds(startOfISOWeekLeft)
  42. var timestampRight =
  43. startOfISOWeekRight.getTime() -
  44. getTimezoneOffsetInMilliseconds(startOfISOWeekRight)
  45. // Round the number of days to the nearest integer
  46. // because the number of milliseconds in a week is not constant
  47. // (e.g. it's different in the week of the daylight saving time clock shift)
  48. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK)
  49. }