You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

53 lines
2.0 KiB

  1. import isValid from '../isValid/index.js';
  2. import isWeekend from '../isWeekend/index.js';
  3. import toDate from '../toDate/index.js';
  4. import differenceInCalendarDays from '../differenceInCalendarDays/index.js';
  5. import addDays from '../addDays/index.js';
  6. import isSameDay from '../isSameDay/index.js';
  7. import toInteger from '../_lib/toInteger/index.js';
  8. import requiredArgs from '../_lib/requiredArgs/index.js';
  9. /**
  10. * @name differenceInBusinessDays
  11. * @category Day Helpers
  12. * @summary Get the number of business days between the given dates.
  13. *
  14. * @description
  15. * Get the number of business day periods between the given dates.
  16. * Business days being days that arent in the weekend.
  17. * Like `differenceInCalendarDays`, the function removes the times from
  18. * the dates before calculating the difference.
  19. *
  20. * @param {Date|Number} dateLeft - the later date
  21. * @param {Date|Number} dateRight - the earlier date
  22. * @returns {Number} the number of business days
  23. * @throws {TypeError} 2 arguments required
  24. *
  25. * @example
  26. * // How many business days are between
  27. * // 10 January 2014 and 20 July 2014?
  28. * var result = differenceInBusinessDays(
  29. * new Date(2014, 6, 20),
  30. * new Date(2014, 0, 10)
  31. * )
  32. * //=> 136
  33. */
  34. export default function differenceInBusinessDays(dirtyDateLeft, dirtyDateRight) {
  35. requiredArgs(2, arguments);
  36. var dateLeft = toDate(dirtyDateLeft);
  37. var dateRight = toDate(dirtyDateRight);
  38. if (!isValid(dateLeft) || !isValid(dateRight)) return new Date(NaN);
  39. var calendarDifference = differenceInCalendarDays(dateLeft, dateRight);
  40. var sign = calendarDifference < 0 ? -1 : 1;
  41. var weeks = toInteger(calendarDifference / 7);
  42. var result = weeks * 5;
  43. dateRight = addDays(dateRight, weeks * 7); // the loop below will run at most 6 times to account for the remaining days that don't makeup a full week
  44. while (!isSameDay(dateLeft, dateRight)) {
  45. // sign is used to account for both negative and positive differences
  46. result += isWeekend(dateRight) ? 0 : sign;
  47. dateRight = addDays(dateRight, sign);
  48. }
  49. return result === 0 ? 0 : result;
  50. }