-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathdate_utils.ts
More file actions
1803 lines (1636 loc) · 45.7 KB
/
date_utils.ts
File metadata and controls
1803 lines (1636 loc) · 45.7 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
addDays,
addHours,
addMinutes,
addMonths,
addQuarters,
addSeconds,
addWeeks,
addYears,
isEqual as dfIsEqual,
isSameDay as dfIsSameDay,
isSameMonth as dfIsSameMonth,
isSameQuarter as dfIsSameQuarter,
isSameYear as dfIsSameYear,
differenceInCalendarDays,
differenceInCalendarMonths,
differenceInCalendarQuarters,
differenceInCalendarYears,
endOfDay,
endOfMonth,
endOfWeek,
endOfYear,
format,
getDate,
getDay,
getHours,
getISOWeek,
getMinutes,
getMonth,
getQuarter,
getSeconds,
getTime,
getYear,
isAfter,
isBefore,
isDate,
isValid as isValidDate,
isWithinInterval,
max,
min,
parse,
parseISO,
set,
setHours,
setMinutes,
setMonth,
setQuarter,
setSeconds,
setYear,
startOfDay,
startOfMonth,
startOfQuarter,
startOfWeek,
startOfYear,
subDays,
subMonths,
subQuarters,
subWeeks,
subYears,
toDate,
} from "date-fns";
import type { Locale as DateFnsLocale, Day } from "date-fns";
// Timezone support types and utilities
// These are dynamically imported when timeZone prop is used
export type TimeZone = string;
interface DateFnsTz {
toZonedTime: (date: Date | number | string, timeZone: string) => Date;
fromZonedTime: (date: Date | number | string, timeZone: string) => Date;
formatInTimeZone: (
date: Date | number | string,
timeZone: string,
formatStr: string,
options?: { locale?: DateFnsLocale },
) => string;
}
// Cache for the date-fns-tz module
let dateFnsTz: DateFnsTz | null = null;
let dateFnsTzLoadAttempted = false;
/**
* Resets the date-fns-tz module cache. Used for testing.
* @internal
*/
export function __resetDateFnsTzCache(): void {
dateFnsTz = null;
dateFnsTzLoadAttempted = false;
}
/**
* Sets the date-fns-tz module to null to simulate it not being installed. Used for testing.
* @internal
*/
export function __setDateFnsTzNull(): void {
dateFnsTz = null;
dateFnsTzLoadAttempted = true;
}
/**
* Attempts to load date-fns-tz module.
* Returns null if the module is not installed.
*/
function getDateFnsTz(): DateFnsTz | null {
if (dateFnsTzLoadAttempted) {
return dateFnsTz;
}
dateFnsTzLoadAttempted = true;
try {
// Dynamic require for date-fns-tz
// Use a variable to prevent webpack from statically analyzing the require
// and showing warnings when the optional dependency is not installed
// See: https://github.com/Hacker0x01/react-datepicker/issues/6154
const dateFnsTzModuleName = "date-fns-tz";
// eslint-disable-next-line @typescript-eslint/no-require-imports
dateFnsTz = require(dateFnsTzModuleName) as DateFnsTz;
} catch {
/* istanbul ignore next - only executes when date-fns-tz is not installed */
dateFnsTz = null;
}
return dateFnsTz;
}
/**
* Converts a date to the specified timezone.
* If no timezone is specified or date-fns-tz is not installed, returns the original date.
*
* @param date - The date to convert
* @param timeZone - The IANA timezone identifier (e.g., "America/New_York", "UTC")
* @returns The date in the specified timezone
*/
export function toZonedTime(date: Date, timeZone?: TimeZone): Date {
if (!timeZone) {
return date;
}
const tz = getDateFnsTz();
if (!tz) {
if (process.env.NODE_ENV !== "production") {
console.warn(
'react-datepicker: timeZone prop requires "date-fns-tz" package. ' +
"Please install it: npm install date-fns-tz",
);
}
return date;
}
return tz.toZonedTime(date, timeZone);
}
/**
* Converts a date from the specified timezone to UTC.
* If no timezone is specified or date-fns-tz is not installed, returns the original date.
*
* @param date - The date in the specified timezone
* @param timeZone - The IANA timezone identifier (e.g., "America/New_York", "UTC")
* @returns The date in UTC
*/
export function fromZonedTime(date: Date, timeZone?: TimeZone): Date {
if (!timeZone) {
return date;
}
const tz = getDateFnsTz();
if (!tz) {
if (process.env.NODE_ENV !== "production") {
console.warn(
'react-datepicker: timeZone prop requires "date-fns-tz" package. ' +
"Please install it: npm install date-fns-tz",
);
}
return date;
}
return tz.fromZonedTime(date, timeZone);
}
/**
* Formats a date in the specified timezone.
* If no timezone is specified, uses the standard format function.
*
* @param date - The date to format
* @param formatStr - The format string
* @param timeZone - The IANA timezone identifier
* @param locale - The locale object
* @returns The formatted date string
*/
export function formatInTimeZone(
date: Date,
formatStr: string,
timeZone?: TimeZone,
locale?: DateFnsLocale,
): string {
if (!timeZone) {
return format(date, formatStr, {
locale,
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
}
const tz = getDateFnsTz();
if (!tz) {
if (process.env.NODE_ENV !== "production") {
console.warn(
'react-datepicker: timeZone prop requires "date-fns-tz" package. ' +
"Please install it: npm install date-fns-tz",
);
}
return format(date, formatStr, {
locale,
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
}
return tz.formatInTimeZone(date, timeZone, formatStr, { locale });
}
/**
* Gets the current date/time in the specified timezone.
*
* @param timeZone - The IANA timezone identifier
* @returns The current date in the specified timezone
*/
export function nowInTimeZone(timeZone?: TimeZone): Date {
const now = new Date();
return toZonedTime(now, timeZone);
}
export type DateNumberType = Day;
interface LocaleObj extends Pick<
DateFnsLocale,
"options" | "formatLong" | "localize" | "match"
> {}
export type Locale = string | LocaleObj;
export enum KeyType {
ArrowUp = "ArrowUp",
ArrowDown = "ArrowDown",
ArrowLeft = "ArrowLeft",
ArrowRight = "ArrowRight",
PageUp = "PageUp",
PageDown = "PageDown",
Home = "Home",
End = "End",
Enter = "Enter",
Space = " ",
Tab = "Tab",
Escape = "Escape",
Backspace = "Backspace",
X = "x",
}
function getLocaleScope() {
// Use this cast to avoid messing with users globalThis (like window) and the rest of keys in the globalThis object we don't care about
const scope = (typeof window !== "undefined"
? window
: globalThis) as unknown as {
__localeId__?: string;
__localeData__: Record<string, LocaleObj>;
};
return scope;
}
export const DEFAULT_YEAR_ITEM_NUMBER = 12;
// ** Date Constructors **
export function newDate(value?: string | Date | number | null): Date {
if (value == null) {
return new Date();
}
const d = typeof value === "string" ? parseISO(value) : toDate(value);
return isValid(d) ? d : new Date();
}
/**
* Parses a date.
*
* @param value - The string representing the Date in a parsable form, e.g., ISO 1861
* @param dateFormat - The date format.
* @param locale - The locale.
* @param strictParsing - The strict parsing flag.
* @param refDate - The base date to be passed to date-fns parse() function.
* @returns - The parsed date or null.
*/
export function parseDate(
value: string,
dateFormat: string | string[],
locale: Locale | undefined,
strictParsing: boolean,
refDate: Date = newDate(),
): Date | null {
const localeObject =
getLocaleObject(locale) || getLocaleObject(getDefaultLocale());
const formats = Array.isArray(dateFormat) ? dateFormat : [dateFormat];
for (const format of formats) {
const parsedDate = parse(value, format, refDate, {
locale: localeObject,
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
if (
isValid(parsedDate) &&
(!strictParsing || value === formatDate(parsedDate, format, locale))
) {
return parsedDate;
}
}
// When strictParsing is false, try native Date parsing as a fallback
// This allows flexible input formats like "12/05/2025" or "2025-12-16"
// even when the dateFormat prop specifies a different format.
// Only attempt this for inputs that look like complete dates (minimum
// length of 8 characters, e.g., "1/1/2000") to avoid parsing partial
// inputs like "03/" or "2000" which should be handled by parseDateForNavigation.
if (!strictParsing && value && value.length >= 8) {
const nativeDate = new Date(value);
if (isValidDate(nativeDate)) {
return nativeDate;
}
}
return null;
}
/**
* Parses a partial date string for calendar navigation purposes.
* Unlike parseDate, this function attempts to extract whatever date
* information is available (year, month) from a partial input,
* returning a date suitable for navigating the calendar view.
*
* @param value - The date string to parse.
* @param refDate - The reference date to use for missing components.
* @returns - A date for navigation or null if no date info could be extracted.
*/
export function parseDateForNavigation(
value: string,
refDate: Date = newDate(),
): Date | null {
if (!value) return null;
// Try to extract a 4-digit year from the input
const yearMatch = value.match(/\b(1\d{3}|2\d{3})\b/);
if (!yearMatch || !yearMatch[1]) return null;
const year = parseInt(yearMatch[1], 10);
// Try to extract a month (1-12) from the input
// Look for patterns like "03/", "/03", "03-", "-03" or standalone "03" at start
const monthMatch = value.match(/(?:^|[/\-\s])?(0?[1-9]|1[0-2])(?:[/\-\s]|$)/);
const month =
monthMatch && monthMatch[1]
? parseInt(monthMatch[1], 10) - 1
: refDate.getMonth();
// Return a date with the extracted year and month, using day 1
return new Date(year, month, 1);
}
// ** Date "Reflection" **
export { isDate, set };
/**
* Checks if a given date is a valid Date object.
* @param date - The date to be checked.
* @returns A boolean value indicating whether the date is valid.
*/
export function isValid(date: Date): boolean {
return isValidDate(date);
}
/**
* Safely returns a valid Date or null.
* This handles cases where a value might be passed as a string or other
* invalid type at runtime, even though TypeScript expects a Date.
* @param date - The value to check (typed as Date but could be anything at runtime)
* @returns The date if it's a valid Date object, otherwise null
*/
export function safeToDate(date: Date | null | undefined): Date | null {
if (date == null) {
return null;
}
// Check if it's actually a Date object AND is valid
if (isDate(date) && isValidDate(date)) {
return date;
}
return null;
}
// ** Date Formatting **
/**
* Formats a date.
*
* @param date - The date.
* @param formatStr - The format string.
* @param locale - The locale.
* @returns - The formatted date.
*/
export function formatDate(
date: Date,
formatStr: string,
locale?: Locale,
): string {
if (locale === "en") {
return format(date, formatStr, {
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
}
let localeObj = locale ? getLocaleObject(locale) : undefined;
if (locale && !localeObj) {
console.warn(
`A locale object was not found for the provided string ["${locale}"].`,
);
}
localeObj = localeObj || getLocaleObject(getDefaultLocale());
return format(date, formatStr, {
locale: localeObj,
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
}
/**
* Safely formats a date.
*
* @param date - The date.
* @param options - An object containing the dateFormat, locale, and optional timeZone.
* @returns - The formatted date or an empty string.
*/
export function safeDateFormat(
date: Date | null | undefined,
{
dateFormat,
locale,
timeZone,
}: { dateFormat: string | string[]; locale?: Locale; timeZone?: TimeZone },
): string {
const formatStr = (
Array.isArray(dateFormat) && dateFormat.length > 0
? dateFormat[0]
: dateFormat
) as string; // Cast to string because it's impossible to get `string | string[] | undefined` here and typescript doesn't know that
if (!date) {
return "";
}
// Use timezone-aware formatting if timeZone is specified
if (timeZone) {
// Resolve locale string to locale object for formatInTimeZone
// Cast to DateFnsLocale since LocaleObj is a compatible subset
const localeObj = (
locale ? getLocaleObject(locale) : getLocaleObject(getDefaultLocale())
) as DateFnsLocale | undefined;
return formatInTimeZone(date, formatStr, timeZone, localeObj);
}
return formatDate(date, formatStr, locale) || "";
}
/**
* Used as a delimiter to separate two dates when formatting a date range
*/
export const DATE_RANGE_SEPARATOR = " - ";
/**
* Safely formats a date range.
*
* @param startDate - The start date.
* @param endDate - The end date.
* @param props - The props.
* @returns - The formatted date range or an empty string.
*/
export function safeDateRangeFormat(
startDate: Date | null | undefined,
endDate: Date | null | undefined,
props: {
dateFormat: string | string[];
locale?: Locale;
rangeSeparator?: string;
timeZone?: TimeZone;
},
): string {
if (!startDate && !endDate) {
return "";
}
const formattedStartDate = startDate ? safeDateFormat(startDate, props) : "";
const formattedEndDate = endDate ? safeDateFormat(endDate, props) : "";
const dateRangeSeparator = props.rangeSeparator || DATE_RANGE_SEPARATOR;
return `${formattedStartDate}${dateRangeSeparator}${formattedEndDate}`;
}
/**
* Safely formats multiple dates.
*
* @param dates - The dates.
* @param props - The props.
* @returns - The formatted dates or an empty string.
*/
export function safeMultipleDatesFormat(
dates: Date[],
props: {
dateFormat: string | string[];
locale?: Locale;
timeZone?: TimeZone;
},
): string {
if (!dates?.length) {
return "";
}
const formattedFirstDate = dates[0] ? safeDateFormat(dates[0], props) : "";
if (dates.length === 1) {
return formattedFirstDate;
}
if (dates.length === 2 && dates[1]) {
const formattedSecondDate = safeDateFormat(dates[1], props);
return `${formattedFirstDate}, ${formattedSecondDate}`;
}
const extraDatesCount = dates.length - 1;
return `${formattedFirstDate} (+${extraDatesCount})`;
}
// ** Date Setters **
/**
* Sets the time for a given date.
*
* @param date - The date.
* @param time - An object containing the hour, minute, and second.
* @returns - The date with the time set.
*/
export function setTime(
date: Date,
{ hour = 0, minute = 0, second = 0 },
): Date {
return setHours(setMinutes(setSeconds(date, second), minute), hour);
}
export { setHours, setMinutes, setMonth, setQuarter, setYear };
// ** Date Getters **
// getDay Returns day of week, getDate returns day of month
export {
getDate,
getDay,
getHours,
getMinutes,
getMonth,
getQuarter,
getSeconds,
getTime,
getYear,
};
/**
* Gets the week of the year for a given date.
*
* @param date - The date.
* @returns - The week of the year.
*/
export function getWeek(date: Date): number {
return getISOWeek(date);
}
/**
* Gets the day-of-the-month code for a given date.
* Returns a zero-padded 3-digit string from "001" to "031".
*
* @param day - The day.
* @returns - A string representing the day of the month (e.g. "001", "002", "003", etc).
*/
export function getDayOfMonthCode(day: Date): string {
return formatDate(day, "ddd");
}
// *** Start of ***
/**
* Gets the start of the day for a given date.
*
* @param date - The date.
* @returns - The start of the day.
*/
export function getStartOfDay(date: Date): Date {
return startOfDay(date);
}
/**
* Gets the start of the week for a given date.
*
* @param date - The date.
* @param locale - The locale.
* @param calendarStartDay - The day the calendar starts on.
* @returns - The start of the week.
*/
export function getStartOfWeek(
date: Date,
locale?: Locale,
calendarStartDay?: Day,
): Date {
const localeObj = locale
? getLocaleObject(locale)
: getLocaleObject(getDefaultLocale());
return startOfWeek(date, {
locale: localeObj,
weekStartsOn: calendarStartDay,
});
}
/**
* Gets the start of the month for a given date.
*
* @param date - The date.
* @returns - The start of the month.
*/
export function getStartOfMonth(date: Date): Date {
return startOfMonth(date);
}
/**
* Gets the start of the year for a given date.
*
* @param date - The date.
* @returns - The start of the year.
*/
export function getStartOfYear(date: Date): Date {
return startOfYear(date);
}
/**
* Gets the start of the quarter for a given date.
*
* @param date - The date.
* @returns - The start of the quarter.
*/
export function getStartOfQuarter(date: Date): Date {
return startOfQuarter(date);
}
/**
* Gets the start of today.
*
* @returns - The start of today.
*/
export function getStartOfToday(): Date {
return startOfDay(newDate());
}
// *** End of ***
/**
* Gets the end of the day for a given date.
*
* @param date - The date.
* @returns - The end of the day.
*/
export function getEndOfDay(date: Date): Date {
return endOfDay(date);
}
/**
* Gets the end of the week for a given date.
*
* @param date - The date.
* @returns - The end of the week.
*/
export function getEndOfWeek(date: Date): Date {
return endOfWeek(date);
}
/**
* Gets the end of the month for a given date.
*
* @param date - The date.
* @returns - The end of the month.
*/
export function getEndOfMonth(date: Date): Date {
return endOfMonth(date);
}
// ** Date Math **
// *** Addition ***
export {
addDays,
addMinutes,
addMonths,
addQuarters,
addSeconds,
addWeeks,
addYears,
};
// *** Subtraction ***
export { addHours, subDays, subMonths, subQuarters, subWeeks, subYears };
// ** Date Comparison **
export { isAfter, isBefore };
/**
* Checks if two dates are in the same year.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are in the same year, false otherwise.
*/
export function isSameYear(date1: Date | null, date2: Date | null): boolean {
if (date1 && date2) {
return dfIsSameYear(date1, date2);
} else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are in the same month.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are in the same month, false otherwise.
*/
export function isSameMonth(date1: Date | null, date2?: Date | null): boolean {
if (date1 && date2) {
return dfIsSameMonth(date1, date2);
} else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are in the same quarter.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are in the same quarter, false otherwise.
*/
export function isSameQuarter(date1: Date | null, date2: Date | null): boolean {
if (date1 && date2) {
return dfIsSameQuarter(date1, date2);
} else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are on the same day.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are on the same day, false otherwise.
*/
export function isSameDay(date1?: Date | null, date2?: Date | null): boolean {
if (date1 && date2) {
return dfIsSameDay(date1, date2);
} else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are equal.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are equal, false otherwise.
*/
export function isEqual(
date1: Date | null | undefined,
date2: Date | null | undefined,
): boolean {
if (date1 && date2) {
return dfIsEqual(date1, date2);
} else {
return !date1 && !date2;
}
}
/**
* Checks if a day is within a date range.
*
* @param day - The day to check.
* @param startDate - The start date of the range.
* @param endDate - The end date of the range.
* @returns - True if the day is within the range, false otherwise.
*/
export function isDayInRange(
day: Date,
startDate: Date,
endDate: Date,
): boolean {
let valid;
const start = startOfDay(startDate);
const end = endOfDay(endDate);
try {
valid = isWithinInterval(day, { start, end });
} catch (err) {
valid = false;
}
return valid;
}
// *** Diffing ***
/**
* Gets the difference in days between two dates.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - The difference in days.
*/
export function getDaysDiff(date1: Date, date2: Date): number {
return differenceInCalendarDays(date1, date2);
}
// ** Date Localization **
/**
* Registers a locale.
*
* @param localeName - The name of the locale.
* @param localeData - The data of the locale.
*/
export function registerLocale(
localeName: string,
localeData: LocaleObj,
): void {
const scope = getLocaleScope();
if (!scope.__localeData__) {
scope.__localeData__ = {};
}
scope.__localeData__[localeName] = localeData;
}
/**
* Sets the default locale.
*
* @param localeName - The name of the locale.
*/
export function setDefaultLocale(localeName?: string): void {
const scope = getLocaleScope();
scope.__localeId__ = localeName;
}
/**
* Gets the default locale.
*
* @returns - The default locale.
*/
export function getDefaultLocale(): string | undefined {
const scope = getLocaleScope();
return scope.__localeId__;
}
/**
* Gets the locale object.
*
* @param localeSpec - The locale specification.
* @returns - The locale object.
*/
export function getLocaleObject(localeSpec?: Locale): LocaleObj | undefined {
if (typeof localeSpec === "string") {
// Treat it as a locale name registered by registerLocale
const scope = getLocaleScope();
// Null was replaced with undefined to avoid type coercion
return scope.__localeData__ ? scope.__localeData__[localeSpec] : undefined;
} else {
// Treat it as a raw date-fns locale object
return localeSpec;
}
}
/**
* Formats the weekday in a given locale.
*
* @param date - The date to format.
* @param formatFunc - The formatting function.
* @param locale - The locale to use for formatting.
* @returns - The formatted weekday.
*/
export function getFormattedWeekdayInLocale(
date: Date,
formatFunc: (date: string) => string,
locale?: Locale,
): string {
return formatFunc(formatDate(date, "EEEE", locale));
}
/**
* Gets the minimum weekday in a given locale.
*
* @param date - The date to format.
* @param locale - The locale to use for formatting.
* @returns - The minimum weekday.
*/
export function getWeekdayMinInLocale(date: Date, locale?: Locale): string {
return formatDate(date, "EEEEEE", locale);
}
/**
* Gets the short weekday in a given locale.
*
* @param date - The date to format.
* @param locale - The locale to use for formatting.
* @returns - The short weekday.
*/
export function getWeekdayShortInLocale(date: Date, locale?: Locale): string {
return formatDate(date, "EEE", locale);
}
/**
* Gets the month in a given locale.
*
* @param month - The month to format.
* @param locale - The locale to use for formatting.
* @returns - The month.
*/
export function getMonthInLocale(month: number, locale?: Locale): string {
return formatDate(setMonth(newDate(), month), "LLLL", locale);
}
/**
* Gets the short month in a given locale.
*
* @param month - The month to format.
* @param locale - The locale to use for formatting.
* @returns - The short month.
*/
export function getMonthShortInLocale(month: number, locale?: Locale): string {
return formatDate(setMonth(newDate(), month), "LLL", locale);
}
/**
* Gets the short quarter in a given locale.
*
* @param quarter - The quarter to format.
* @param locale - The locale to use for formatting.
* @returns - The short quarter.
*/
export function getQuarterShortInLocale(
quarter: number,
locale?: Locale,
): string {
return formatDate(setQuarter(newDate(), quarter), "QQQ", locale);
}
// ** Utils for some components **
export interface DateFilterOptions {
minDate?: Date;
maxDate?: Date;
excludeDates?: { date: Date; message?: string }[] | Date[];
excludeDateIntervals?: { start: Date; end: Date }[];
includeDates?: Date[];
includeDateIntervals?: { start: Date; end: Date }[];
filterDate?: (date: Date) => boolean;
yearItemNumber?: number;
}
export type DateFilterOptionsWithDisabled = DateFilterOptions & {
disabled?: boolean;
};
/**
* Checks if a day is disabled.
*
* @param day - The day to check.
* @param options - The options to consider when checking.
* @returns - Returns true if the day is disabled, false otherwise.
*/
export function isDayDisabled(
day: Date,
{
minDate,