UNPKG

1.22 kBPlain TextView Raw
1import { dateLib as defaultDateLib } from "../lib/index.js";
2import type { DateRange, DateLib } from "../types/index.js";
3
4/**
5 * Determines whether a given date is inside a specified date range.
6 *
7 * @since 9.0.0
8 * @group Utilities
9 */
10export function rangeIncludesDate(
11 range: DateRange,
12 date: Date,
13 /** If `true`, the ends of the range are excluded. */
14 excludeEnds = false,
15 /** @ignore */
16 dateLib: DateLib = defaultDateLib
17): boolean {
18 let { from, to } = range;
19 const { differenceInCalendarDays, isSameDay } = dateLib;
20 if (from && to) {
21 const isRangeInverted = differenceInCalendarDays(to, from) < 0;
22 if (isRangeInverted) {
23 [from, to] = [to, from];
24 }
25 const isInRange =
26 differenceInCalendarDays(date, from) >= (excludeEnds ? 1 : 0) &&
27 differenceInCalendarDays(to, date) >= (excludeEnds ? 1 : 0);
28 return isInRange;
29 }
30 if (!excludeEnds && to) {
31 return isSameDay(to, date);
32 }
33 if (!excludeEnds && from) {
34 return isSameDay(from, date);
35 }
36 return false;
37}
38
39/**
40 * @private
41 * @deprecated Use {@link rangeIncludesDate} instead.
42 */
43export const isDateInRange = (range: DateRange, date: Date) =>
44 rangeIncludesDate(range, date, false, defaultDateLib);