index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var startOfWeek = require('../start_of_week/index.js')
  2. var MILLISECONDS_IN_MINUTE = 60000
  3. var MILLISECONDS_IN_WEEK = 604800000
  4. /**
  5. * @category Week Helpers
  6. * @summary Get the number of calendar weeks between the given dates.
  7. *
  8. * @description
  9. * Get the number of calendar weeks between the given dates.
  10. *
  11. * @param {Date|String|Number} dateLeft - the later date
  12. * @param {Date|String|Number} dateRight - the earlier date
  13. * @param {Object} [options] - the object with options
  14. * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  15. * @returns {Number} the number of calendar weeks
  16. *
  17. * @example
  18. * // How many calendar weeks are between 5 July 2014 and 20 July 2014?
  19. * var result = differenceInCalendarWeeks(
  20. * new Date(2014, 6, 20),
  21. * new Date(2014, 6, 5)
  22. * )
  23. * //=> 3
  24. *
  25. * @example
  26. * // If the week starts on Monday,
  27. * // how many calendar weeks are between 5 July 2014 and 20 July 2014?
  28. * var result = differenceInCalendarWeeks(
  29. * new Date(2014, 6, 20),
  30. * new Date(2014, 6, 5),
  31. * {weekStartsOn: 1}
  32. * )
  33. * //=> 2
  34. */
  35. function differenceInCalendarWeeks (dirtyDateLeft, dirtyDateRight, dirtyOptions) {
  36. var startOfWeekLeft = startOfWeek(dirtyDateLeft, dirtyOptions)
  37. var startOfWeekRight = startOfWeek(dirtyDateRight, dirtyOptions)
  38. var timestampLeft = startOfWeekLeft.getTime() -
  39. startOfWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE
  40. var timestampRight = startOfWeekRight.getTime() -
  41. startOfWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE
  42. // Round the number of days to the nearest integer
  43. // because the number of milliseconds in a week is not constant
  44. // (e.g. it's different in the week of the daylight saving time clock shift)
  45. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK)
  46. }
  47. module.exports = differenceInCalendarWeeks