index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import isWeekend from "../isWeekend/index.js";
  2. import toDate from "../toDate/index.js";
  3. import toInteger from "../_lib/toInteger/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. import isSunday from "../isSunday/index.js";
  6. import isSaturday from "../isSaturday/index.js";
  7. /**
  8. * @name addBusinessDays
  9. * @category Day Helpers
  10. * @summary Add the specified number of business days (mon - fri) to the given date.
  11. *
  12. * @description
  13. * Add the specified number of business days (mon - fri) to the given date, ignoring weekends.
  14. *
  15. * @param {Date|Number} date - the date to be changed
  16. * @param {Number} amount - the amount of business days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
  17. * @returns {Date} the new date with the business days added
  18. * @throws {TypeError} 2 arguments required
  19. *
  20. * @example
  21. * // Add 10 business days to 1 September 2014:
  22. * const result = addBusinessDays(new Date(2014, 8, 1), 10)
  23. * //=> Mon Sep 15 2014 00:00:00 (skipped weekend days)
  24. */
  25. export default function addBusinessDays(dirtyDate, dirtyAmount) {
  26. requiredArgs(2, arguments);
  27. var date = toDate(dirtyDate);
  28. var startedOnWeekend = isWeekend(date);
  29. var amount = toInteger(dirtyAmount);
  30. if (isNaN(amount)) return new Date(NaN);
  31. var hours = date.getHours();
  32. var sign = amount < 0 ? -1 : 1;
  33. var fullWeeks = toInteger(amount / 5);
  34. date.setDate(date.getDate() + fullWeeks * 7);
  35. // Get remaining days not part of a full week
  36. var restDays = Math.abs(amount % 5);
  37. // Loops over remaining days
  38. while (restDays > 0) {
  39. date.setDate(date.getDate() + sign);
  40. if (!isWeekend(date)) restDays -= 1;
  41. }
  42. // If the date is a weekend day and we reduce a dividable of
  43. // 5 from it, we land on a weekend date.
  44. // To counter this, we add days accordingly to land on the next business day
  45. if (startedOnWeekend && isWeekend(date) && amount !== 0) {
  46. // If we're reducing days, we want to add days until we land on a weekday
  47. // If we're adding days we want to reduce days until we land on a weekday
  48. if (isSaturday(date)) date.setDate(date.getDate() + (sign < 0 ? 2 : -1));
  49. if (isSunday(date)) date.setDate(date.getDate() + (sign < 0 ? 1 : -2));
  50. }
  51. // Restore hours to avoid DST lag
  52. date.setHours(hours);
  53. return date;
  54. }