-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.ts
68 lines (63 loc) · 2.56 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { getTimezoneOffsetInMilliseconds } from "../_lib/getTimezoneOffsetInMilliseconds/index.js";
import { millisecondsInDay } from "../constants/index.js";
import { toDate } from "../toDate/index.js";
import type { Interval } from "../types.js";
/**
* @name getOverlappingDaysInIntervals
* @category Interval Helpers
* @summary Get the number of days that overlap in two time intervals
*
* @description
* Get the number of days that overlap in two time intervals. It uses the time
* between dates to calculate the number of days, rounding it up to include
* partial days.
*
* Two equal 0-length intervals will result in 0. Two equal 1ms intervals will
* result in 1.
*
* @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).
*
* @param intervalLeft - The first interval to compare.
* @param intervalRight - The second interval to compare.
*
* @returns The number of days that overlap in two time intervals
*
* @example
* // For overlapping time intervals adds 1 for each started overlapping day:
* getOverlappingDaysInIntervals(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
* )
* //=> 3
*
* @example
* // For non-overlapping time intervals returns 0:
* getOverlappingDaysInIntervals(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }
* )
* //=> 0
*/
export function getOverlappingDaysInIntervals<DateType extends Date>(
intervalLeft: Interval<DateType>,
intervalRight: Interval<DateType>,
): number {
const [leftStart, leftEnd] = [
+toDate(intervalLeft.start),
+toDate(intervalLeft.end),
].sort((a, b) => a - b);
const [rightStart, rightEnd] = [
+toDate(intervalRight.start),
+toDate(intervalRight.end),
].sort((a, b) => a - b);
// Prevent NaN result if intervals don't overlap at all.
const isOverlapping = leftStart < rightEnd && rightStart < leftEnd;
if (!isOverlapping) return 0;
// Remove the timezone offset to negate the DST effect on calculations.
const overlapLeft = rightStart < leftStart ? leftStart : rightStart;
const left = overlapLeft - getTimezoneOffsetInMilliseconds(overlapLeft);
const overlapRight = rightEnd > leftEnd ? leftEnd : rightEnd;
const right = overlapRight - getTimezoneOffsetInMilliseconds(overlapRight);
// Ceil the number to include partial days too.
return Math.ceil((right - left) / millisecondsInDay);
}