addBusinessDays.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. exports.addBusinessDays = addBusinessDays;
  3. var _index = require("./constructFrom.js");
  4. var _index2 = require("./isSaturday.js");
  5. var _index3 = require("./isSunday.js");
  6. var _index4 = require("./isWeekend.js");
  7. var _index5 = require("./toDate.js");
  8. /**
  9. * @name addBusinessDays
  10. * @category Date Extension Helpers
  11. * @summary Add the specified number of business days (mon - fri) to the given date.
  12. *
  13. * @description
  14. * Add the specified number of business days (mon - fri) to the given date, ignoring weekends.
  15. *
  16. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  17. *
  18. * @param date - The date to be changed
  19. * @param amount - The amount of business days to be added.
  20. *
  21. * @returns The new date with the business days added
  22. *
  23. * @example
  24. * // Add 10 business days to 1 September 2014:
  25. * const result = addBusinessDays(new Date(2014, 8, 1), 10)
  26. * //=> Mon Sep 15 2014 00:00:00 (skipped weekend days)
  27. */
  28. function addBusinessDays(date, amount) {
  29. const _date = (0, _index5.toDate)(date);
  30. const startedOnWeekend = (0, _index4.isWeekend)(_date);
  31. if (isNaN(amount)) return (0, _index.constructFrom)(date, NaN);
  32. const hours = _date.getHours();
  33. const sign = amount < 0 ? -1 : 1;
  34. const fullWeeks = Math.trunc(amount / 5);
  35. _date.setDate(_date.getDate() + fullWeeks * 7);
  36. // Get remaining days not part of a full week
  37. let restDays = Math.abs(amount % 5);
  38. // Loops over remaining days
  39. while (restDays > 0) {
  40. _date.setDate(_date.getDate() + sign);
  41. if (!(0, _index4.isWeekend)(_date)) restDays -= 1;
  42. }
  43. // If the date is a weekend day and we reduce a dividable of
  44. // 5 from it, we land on a weekend date.
  45. // To counter this, we add days accordingly to land on the next business day
  46. if (startedOnWeekend && (0, _index4.isWeekend)(_date) && amount !== 0) {
  47. // If we're reducing days, we want to add days until we land on a weekday
  48. // If we're adding days we want to reduce days until we land on a weekday
  49. if ((0, _index2.isSaturday)(_date))
  50. _date.setDate(_date.getDate() + (sign < 0 ? 2 : -1));
  51. if ((0, _index3.isSunday)(_date))
  52. _date.setDate(_date.getDate() + (sign < 0 ? 1 : -2));
  53. }
  54. // Restore hours to avoid DST lag
  55. _date.setHours(hours);
  56. return _date;
  57. }