index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var parse = require('../parse/index.js')
  2. var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000
  3. /**
  4. * @category Range Helpers
  5. * @summary Get the number of days that overlap in two date ranges
  6. *
  7. * @description
  8. * Get the number of days that overlap in two date ranges
  9. *
  10. * @param {Date|String|Number} initialRangeStartDate - the start of the initial range
  11. * @param {Date|String|Number} initialRangeEndDate - the end of the initial range
  12. * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with
  13. * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with
  14. * @returns {Number} the number of days that overlap in two date ranges
  15. * @throws {Error} startDate of a date range cannot be after its endDate
  16. *
  17. * @example
  18. * // For overlapping date ranges adds 1 for each started overlapping day:
  19. * getOverlappingDaysInRanges(
  20. * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21)
  21. * )
  22. * //=> 3
  23. *
  24. * @example
  25. * // For non-overlapping date ranges returns 0:
  26. * getOverlappingDaysInRanges(
  27. * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22)
  28. * )
  29. * //=> 0
  30. */
  31. function getOverlappingDaysInRanges (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) {
  32. var initialStartTime = parse(dirtyInitialRangeStartDate).getTime()
  33. var initialEndTime = parse(dirtyInitialRangeEndDate).getTime()
  34. var comparedStartTime = parse(dirtyComparedRangeStartDate).getTime()
  35. var comparedEndTime = parse(dirtyComparedRangeEndDate).getTime()
  36. if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) {
  37. throw new Error('The start of the range cannot be after the end of the range')
  38. }
  39. var isOverlapping = initialStartTime < comparedEndTime && comparedStartTime < initialEndTime
  40. if (!isOverlapping) {
  41. return 0
  42. }
  43. var overlapStartDate = comparedStartTime < initialStartTime
  44. ? initialStartTime
  45. : comparedStartTime
  46. var overlapEndDate = comparedEndTime > initialEndTime
  47. ? initialEndTime
  48. : comparedEndTime
  49. var differenceInMs = overlapEndDate - overlapStartDate
  50. return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY)
  51. }
  52. module.exports = getOverlappingDaysInRanges