1 | import { toDate } from "./toDate.js";
|
2 |
|
3 | /**
|
4 | * The {@link isWithinInterval} function options.
|
5 | */
|
6 |
|
7 | /**
|
8 | * @name isWithinInterval
|
9 | * @category Interval Helpers
|
10 | * @summary Is the given date within the interval?
|
11 | *
|
12 | * @description
|
13 | * Is the given date within the interval? (Including start and end.)
|
14 | *
|
15 | * @param date - The date to check
|
16 | * @param interval - The interval to check
|
17 | * @param options - An object with options
|
18 | *
|
19 | * @returns The date is within the interval
|
20 | *
|
21 | * @example
|
22 | * // For the date within the interval:
|
23 | * isWithinInterval(new Date(2014, 0, 3), {
|
24 | * start: new Date(2014, 0, 1),
|
25 | * end: new Date(2014, 0, 7)
|
26 | * })
|
27 | * // => true
|
28 | *
|
29 | * @example
|
30 | * // For the date outside of the interval:
|
31 | * isWithinInterval(new Date(2014, 0, 10), {
|
32 | * start: new Date(2014, 0, 1),
|
33 | * end: new Date(2014, 0, 7)
|
34 | * })
|
35 | * // => false
|
36 | *
|
37 | * @example
|
38 | * // For date equal to the interval start:
|
39 | * isWithinInterval(date, { start, end: date })
|
40 | * // => true
|
41 | *
|
42 | * @example
|
43 | * // For date equal to the interval end:
|
44 | * isWithinInterval(date, { start: date, end })
|
45 | * // => true
|
46 | */
|
47 | export function isWithinInterval(date, interval, options) {
|
48 | const time = +toDate(date, options?.in);
|
49 | const [startTime, endTime] = [
|
50 | +toDate(interval.start, options?.in),
|
51 | +toDate(interval.end, options?.in),
|
52 | ].sort((a, b) => a - b);
|
53 |
|
54 | return time >= startTime && time <= endTime;
|
55 | }
|
56 |
|
57 | // Fallback for modularized imports:
|
58 | export default isWithinInterval;
|