UNPKG

2.83 kBJavaScriptView Raw
1"use strict";
2exports.differenceInBusinessDays = differenceInBusinessDays;
3var _index = require("./addDays.js");
4var _index2 = require("./differenceInCalendarDays.js");
5var _index3 = require("./isSameDay.js");
6var _index4 = require("./isValid.js");
7var _index5 = require("./isWeekend.js");
8var _index6 = require("./toDate.js");
9
10/**
11 * @name differenceInBusinessDays
12 * @category Day Helpers
13 * @summary Get the number of business days between the given dates.
14 *
15 * @description
16 * Get the number of business day periods between the given dates.
17 * Business days being days that arent in the weekend.
18 * Like `differenceInCalendarDays`, the function removes the times from
19 * the dates before calculating the difference.
20 *
21 * @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).
22 *
23 * @param dateLeft - The later date
24 * @param dateRight - The earlier date
25 *
26 * @returns The number of business days
27 *
28 * @example
29 * // How many business days are between
30 * // 10 January 2014 and 20 July 2014?
31 * const result = differenceInBusinessDays(
32 * new Date(2014, 6, 20),
33 * new Date(2014, 0, 10)
34 * )
35 * //=> 136
36 *
37 * // How many business days are between
38 * // 30 November 2021 and 1 November 2021?
39 * const result = differenceInBusinessDays(
40 * new Date(2021, 10, 30),
41 * new Date(2021, 10, 1)
42 * )
43 * //=> 21
44 *
45 * // How many business days are between
46 * // 1 November 2021 and 1 December 2021?
47 * const result = differenceInBusinessDays(
48 * new Date(2021, 10, 1),
49 * new Date(2021, 11, 1)
50 * )
51 * //=> -22
52 *
53 * // How many business days are between
54 * // 1 November 2021 and 1 November 2021 ?
55 * const result = differenceInBusinessDays(
56 * new Date(2021, 10, 1),
57 * new Date(2021, 10, 1)
58 * )
59 * //=> 0
60 */
61function differenceInBusinessDays(dateLeft, dateRight) {
62 const _dateLeft = (0, _index6.toDate)(dateLeft);
63 let _dateRight = (0, _index6.toDate)(dateRight);
64
65 if (!(0, _index4.isValid)(_dateLeft) || !(0, _index4.isValid)(_dateRight))
66 return NaN;
67
68 const calendarDifference = (0, _index2.differenceInCalendarDays)(
69 _dateLeft,
70 _dateRight,
71 );
72 const sign = calendarDifference < 0 ? -1 : 1;
73
74 const weeks = Math.trunc(calendarDifference / 7);
75
76 let result = weeks * 5;
77 _dateRight = (0, _index.addDays)(_dateRight, weeks * 7);
78
79 // the loop below will run at most 6 times to account for the remaining days that don't makeup a full week
80 while (!(0, _index3.isSameDay)(_dateLeft, _dateRight)) {
81 // sign is used to account for both negative and positive differences
82 result += (0, _index5.isWeekend)(_dateRight) ? 0 : sign;
83 _dateRight = (0, _index.addDays)(_dateRight, sign);
84 }
85
86 // Prevent negative zero
87 return result === 0 ? 0 : result;
88}