0
# Date Utilities
1
2
React Day Picker provides utility functions for working with dates, date ranges, intervals, and matching patterns.
3
4
## Capabilities
5
6
### Date Range Operations
7
8
Utilities for creating, manipulating, and validating date ranges.
9
10
```typescript { .api }
11
/**
12
* Date range interface
13
*/
14
interface DateRange {
15
from: Date | undefined;
16
to?: Date | undefined;
17
}
18
19
/**
20
* Adds a date to an existing range, considering constraints like minimum and
21
* maximum range size.
22
* @param date - The date to add to the range
23
* @param initialRange - The initial range to which the date will be added
24
* @param min - The minimum number of days in the range
25
* @param max - The maximum number of days in the range
26
* @param required - Whether the range must always include at least one date
27
* @param dateLib - The date utility library instance
28
* @returns The updated date range, or undefined if the range is cleared
29
*/
30
function addToRange(
31
date: Date,
32
initialRange: DateRange | undefined,
33
min?: number,
34
max?: number,
35
required?: boolean,
36
dateLib?: DateLib
37
): DateRange | undefined;
38
39
/**
40
* Check if a date is included in a date range
41
* @param range - The date range to check
42
* @param date - The date to check for inclusion
43
* @param excludeEnds - Whether to exclude the start and end dates
44
* @param dateLib - Optional DateLib instance for date operations
45
* @returns True if date is within the range
46
*/
47
function rangeIncludesDate(
48
range: DateRange,
49
date: Date,
50
excludeEnds?: boolean,
51
dateLib?: DateLib
52
): boolean;
53
54
/**
55
* Determines if two date ranges overlap
56
* @param rangeLeft - The first date range
57
* @param rangeRight - The second date range
58
* @param dateLib - The date utility library instance
59
* @returns True if the ranges overlap, otherwise false
60
*/
61
function rangeOverlaps(
62
rangeLeft: { from: Date; to: Date },
63
rangeRight: { from: Date; to: Date },
64
dateLib?: DateLib
65
): boolean;
66
67
/**
68
* Checks if a date range contains one or more specified days of the week
69
* @param range - The date range to check
70
* @param dayOfWeek - The day(s) of the week to check for (0-6, where 0 is Sunday)
71
* @param dateLib - The date utility library instance
72
* @returns True if the range contains the specified day(s) of the week, otherwise false
73
*/
74
function rangeContainsDayOfWeek(
75
range: { from: Date; to: Date },
76
dayOfWeek: number | number[],
77
dateLib?: DateLib
78
): boolean;
79
80
/**
81
* Checks if a date range contains dates that match the given modifiers
82
* @param range - The date range to check
83
* @param modifiers - The modifiers to match against
84
* @param dateLib - The date utility library instance
85
* @returns True if the range contains matching dates, otherwise false
86
*/
87
function rangeContainsModifiers(
88
range: { from: Date; to: Date },
89
modifiers: Matcher | Matcher[],
90
dateLib?: DateLib
91
): boolean;
92
```
93
94
**Usage Examples:**
95
96
```typescript
97
import {
98
addToRange,
99
rangeIncludesDate,
100
rangeOverlaps,
101
type DateRange
102
} from "react-day-picker";
103
104
// Building a date range interactively
105
function InteractiveRange() {
106
const [range, setRange] = useState<DateRange | undefined>();
107
108
const handleDateClick = (date: Date) => {
109
// Add clicked date to range with max 14 days constraint
110
const newRange = addToRange(date, range, { max: 14 });
111
setRange(newRange);
112
};
113
114
return (
115
<DayPicker
116
mode="single"
117
onDayClick={handleDateClick}
118
selected={range?.from}
119
modifiers={{
120
range_start: range?.from,
121
range_end: range?.to,
122
range_middle: (date: Date) =>
123
range ? rangeIncludesDate(range, date, true) : false
124
}}
125
/>
126
);
127
}
128
129
// Check for overlapping vacation periods
130
function VacationChecker() {
131
const vacation1: DateRange = {
132
from: new Date(2024, 6, 10),
133
to: new Date(2024, 6, 20)
134
};
135
136
const vacation2: DateRange = {
137
from: new Date(2024, 6, 15),
138
to: new Date(2024, 6, 25)
139
};
140
141
const hasOverlap = rangeOverlaps(vacation1, vacation2);
142
console.log(`Vacations overlap: ${hasOverlap}`); // true
143
144
return (
145
<DayPicker
146
mode="range"
147
modifiers={{
148
vacation1: vacation1,
149
vacation2: vacation2,
150
overlap: (date: Date) =>
151
rangeIncludesDate(vacation1, date) &&
152
rangeIncludesDate(vacation2, date)
153
}}
154
/>
155
);
156
}
157
158
// Check if range includes weekends
159
const businessRange: DateRange = {
160
from: new Date(2024, 6, 1),
161
to: new Date(2024, 6, 31)
162
};
163
164
const includesWeekends = rangeContainsDayOfWeek(
165
businessRange,
166
[0, 6] // Sunday and Saturday
167
);
168
```
169
170
### Date Matching System
171
172
Utilities for matching dates against various criteria.
173
174
```typescript { .api }
175
/**
176
* Checks if a given date matches at least one of the specified Matcher
177
* @param date - The date to check
178
* @param matchers - The matchers to check against
179
* @param dateLib - The date utility library instance
180
* @returns True if the date matches any of the matchers, otherwise false
181
*/
182
function dateMatchModifiers(
183
date: Date,
184
matchers: Matcher | Matcher[],
185
dateLib?: DateLib
186
): boolean;
187
188
/**
189
* Union type for various date matching patterns
190
*/
191
type Matcher =
192
| boolean
193
| ((date: Date) => boolean)
194
| Date
195
| Date[]
196
| DateRange
197
| DateInterval
198
| DateBefore
199
| DateAfter
200
| DayOfWeek;
201
202
/**
203
* Date interval matcher (between two dates)
204
*/
205
interface DateInterval {
206
before: Date;
207
after: Date;
208
}
209
210
/**
211
* Before date matcher
212
*/
213
interface DateBefore {
214
before: Date;
215
}
216
217
/**
218
* After date matcher
219
*/
220
interface DateAfter {
221
after: Date;
222
}
223
224
/**
225
* Day of week matcher
226
*/
227
interface DayOfWeek {
228
dayOfWeek: number | number[];
229
}
230
```
231
232
**Usage Examples:**
233
234
```typescript
235
import { dateMatchModifiers, type Matcher } from "react-day-picker";
236
237
// Complex date matching
238
const matchers: Matcher[] = [
239
new Date(2024, 6, 4), // July 4th
240
{ before: new Date(2024, 0, 1) }, // Before New Year
241
{ after: new Date(2024, 11, 31) }, // After New Year's Eve
242
{ dayOfWeek: [0, 6] }, // Weekends
243
{ before: new Date(2024, 6, 1), after: new Date(2024, 5, 1) }, // June
244
(date: Date) => date.getDate() === 13 // Friday the 13th check elsewhere
245
];
246
247
const testDate = new Date(2024, 6, 4);
248
const matches = dateMatchModifiers(testDate, matchers);
249
console.log(`Date matches: ${matches}`); // true (July 4th)
250
```
251
252
### Type Guards
253
254
Utility functions to determine the type of matchers and values.
255
256
```typescript { .api }
257
/**
258
* Checks if the given value is of type DateRange
259
* @param value - The value to check
260
* @returns True if the value is a DateRange, otherwise false
261
*/
262
function isDateRange(value: unknown): value is DateRange;
263
264
/**
265
* Checks if the given value is of type DateInterval
266
* @param matcher - The value to check
267
* @returns True if the value is a DateInterval, otherwise false
268
*/
269
function isDateInterval(matcher: unknown): matcher is DateInterval;
270
271
/**
272
* Checks if the given value is of type DateAfter
273
* @param value - The value to check
274
* @returns True if the value is a DateAfter, otherwise false
275
*/
276
function isDateAfterType(value: unknown): value is DateAfter;
277
278
/**
279
* Checks if the given value is of type DateBefore
280
* @param value - The value to check
281
* @returns True if the value is a DateBefore, otherwise false
282
*/
283
function isDateBeforeType(value: unknown): value is DateBefore;
284
285
/**
286
* Checks if the given value is an array of valid dates
287
* @param value - The value to check
288
* @param dateLib - The date utility library instance
289
* @returns True if the value is an array of valid dates, otherwise false
290
*/
291
function isDatesArray(value: unknown, dateLib: DateLib): value is Date[];
292
293
/**
294
* Checks if the given value is of type DayOfWeek
295
* @param value - The value to check
296
* @returns True if the value is a DayOfWeek, otherwise false
297
*/
298
function isDayOfWeekType(value: unknown): value is DayOfWeek;
299
```
300
301
**Usage Examples:**
302
303
```typescript
304
import {
305
isDateRange,
306
isDateInterval,
307
isDayOfWeekType,
308
type DateRange,
309
type DateInterval,
310
type DayOfWeek
311
} from "react-day-picker";
312
313
function processDateMatcher(matcher: any) {
314
if (isDateRange(matcher)) {
315
console.log(`Range from ${matcher.from} to ${matcher.to}`);
316
} else if (isDateInterval(matcher)) {
317
console.log(`Interval between ${matcher.after} and ${matcher.before}`);
318
} else if (isDayOfWeekType(matcher)) {
319
const days = Array.isArray(matcher.dayOfWeek)
320
? matcher.dayOfWeek
321
: [matcher.dayOfWeek];
322
console.log(`Days of week: ${days.join(', ')}`);
323
}
324
}
325
326
// Usage in component
327
function SmartCalendar({ disabledDates }: { disabledDates: any[] }) {
328
const processedDisabled = disabledDates.filter(matcher => {
329
// Only include valid matchers
330
return isDateRange(matcher) ||
331
isDateInterval(matcher) ||
332
isDayOfWeekType(matcher) ||
333
matcher instanceof Date ||
334
typeof matcher === 'function';
335
});
336
337
return (
338
<DayPicker
339
disabled={processedDisabled}
340
modifiers={{
341
weekend: { dayOfWeek: [0, 6] },
342
holiday: [
343
new Date(2024, 6, 4),
344
new Date(2024, 11, 25)
345
]
346
}}
347
/>
348
);
349
}
350
```
351
352
### Helper Functions
353
354
Additional utility functions for common calendar operations.
355
356
```typescript { .api }
357
/**
358
* Get default CSS class names for all UI elements
359
* @returns Complete ClassNames mapping with default values
360
*/
361
function getDefaultClassNames(): ClassNames;
362
363
/**
364
* Calculate focus target for keyboard navigation
365
* @param focusTarget - Current focus target
366
* @param moveBy - Type of movement
367
* @param moveDir - Direction of movement
368
* @param focusableDate - Date that can receive focus
369
* @param dateLib - DateLib instance
370
* @returns New focus target date
371
*/
372
function calculateFocusTarget(
373
focusTarget: CalendarDay,
374
moveBy: MoveFocusBy,
375
moveDir: MoveFocusDir,
376
focusableDate: Date,
377
dateLib: DateLib
378
): Date;
379
380
/**
381
* Movement types for keyboard navigation
382
*/
383
type MoveFocusBy =
384
| "day"
385
| "week"
386
| "month"
387
| "year"
388
| "startOfWeek"
389
| "endOfWeek";
390
391
/**
392
* Movement directions
393
*/
394
type MoveFocusDir = "before" | "after";
395
```
396
397
**Usage Examples:**
398
399
```typescript
400
import { getDefaultClassNames } from "react-day-picker";
401
402
// Get default class names for customization
403
const defaultClassNames = getDefaultClassNames();
404
const customClassNames = {
405
...defaultClassNames,
406
day: `${defaultClassNames.day} my-custom-day`,
407
selected: `${defaultClassNames.selected} my-selected-day`
408
};
409
410
<DayPicker classNames={customClassNames} />
411
412
// Custom keyboard navigation handler
413
function CustomNavigationCalendar() {
414
const handleKeyDown = (
415
date: Date,
416
modifiers: Modifiers,
417
e: React.KeyboardEvent
418
) => {
419
if (e.key === 'Enter') {
420
console.log(`Selected date: ${date.toDateString()}`);
421
}
422
};
423
424
return (
425
<DayPicker
426
mode="single"
427
onDayKeyDown={handleKeyDown}
428
/>
429
);
430
}
431
```