1 | import { toDate } from "./toDate.mjs";
|
2 |
|
3 | /**
|
4 | * The {@link eachDayOfInterval} function options.
|
5 | */
|
6 |
|
7 | /**
|
8 | * @name eachDayOfInterval
|
9 | * @category Interval Helpers
|
10 | * @summary Return the array of dates within the specified time interval.
|
11 | *
|
12 | * @description
|
13 | * Return the array of dates within the specified time interval.
|
14 | *
|
15 | * @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).
|
16 | *
|
17 | * @param interval - The interval.
|
18 | * @param options - An object with options.
|
19 | *
|
20 | * @returns The array with starts of days from the day of the interval start to the day of the interval end
|
21 | *
|
22 | * @example
|
23 | * // Each day between 6 October 2014 and 10 October 2014:
|
24 | * const result = eachDayOfInterval({
|
25 | * start: new Date(2014, 9, 6),
|
26 | * end: new Date(2014, 9, 10)
|
27 | * })
|
28 | * //=> [
|
29 | * // Mon Oct 06 2014 00:00:00,
|
30 | * // Tue Oct 07 2014 00:00:00,
|
31 | * // Wed Oct 08 2014 00:00:00,
|
32 | * // Thu Oct 09 2014 00:00:00,
|
33 | * // Fri Oct 10 2014 00:00:00
|
34 | * // ]
|
35 | */
|
36 | export function eachDayOfInterval(interval, options) {
|
37 | const startDate = toDate(interval.start);
|
38 | const endDate = toDate(interval.end);
|
39 |
|
40 | let reversed = +startDate > +endDate;
|
41 | const endTime = reversed ? +startDate : +endDate;
|
42 | const currentDate = reversed ? endDate : startDate;
|
43 | currentDate.setHours(0, 0, 0, 0);
|
44 |
|
45 | let step = options?.step ?? 1;
|
46 | if (!step) return [];
|
47 | if (step < 0) {
|
48 | step = -step;
|
49 | reversed = !reversed;
|
50 | }
|
51 |
|
52 | const dates = [];
|
53 |
|
54 | while (+currentDate <= endTime) {
|
55 | dates.push(toDate(currentDate));
|
56 | currentDate.setDate(currentDate.getDate() + step);
|
57 | currentDate.setHours(0, 0, 0, 0);
|
58 | }
|
59 |
|
60 | return reversed ? dates.reverse() : dates;
|
61 | }
|
62 |
|
63 | // Fallback for modularized imports:
|
64 | export default eachDayOfInterval;
|