@bigbinary/neeto-atoms 1.0.37 → 1.0.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/DatePicker-CJfkNORC.js +634 -0
  2. package/dist/DatePicker-CJfkNORC.js.map +1 -0
  3. package/dist/{TimePicker-wPi2k6Z8.js → TimePicker-D4cwQB7b.js} +50 -32
  4. package/dist/TimePicker-D4cwQB7b.js.map +1 -0
  5. package/dist/TimePickerPanel-DN5mK2he.js +436 -0
  6. package/dist/TimePickerPanel-DN5mK2he.js.map +1 -0
  7. package/dist/cjs/DatePicker-DaVdS--q.js +636 -0
  8. package/dist/cjs/DatePicker-DaVdS--q.js.map +1 -0
  9. package/dist/cjs/{TimePicker-BG_vYH3r.js → TimePicker-DrHKSjhU.js} +49 -31
  10. package/dist/cjs/TimePicker-DrHKSjhU.js.map +1 -0
  11. package/dist/cjs/TimePickerPanel-Df904uM-.js +446 -0
  12. package/dist/cjs/TimePickerPanel-Df904uM-.js.map +1 -0
  13. package/dist/cjs/components/DatePicker.js +4 -3
  14. package/dist/cjs/components/DatePicker.js.map +1 -1
  15. package/dist/cjs/components/TimePicker.js +3 -2
  16. package/dist/cjs/components/TimePicker.js.map +1 -1
  17. package/dist/cjs/components/index.js +5 -4
  18. package/dist/cjs/components/index.js.map +1 -1
  19. package/dist/cjs/index.js +11 -247
  20. package/dist/cjs/index.js.map +1 -1
  21. package/dist/cjs/primitives/Calendar.js +8129 -10
  22. package/dist/cjs/primitives/Calendar.js.map +1 -1
  23. package/dist/cjs/primitives/index.js +1 -1
  24. package/dist/components/DatePicker/constants.d.ts +0 -1
  25. package/dist/components/DatePicker/types.d.ts +7 -5
  26. package/dist/components/DatePicker/utils.d.ts +18 -3
  27. package/dist/components/DatePicker.js +4 -3
  28. package/dist/components/DatePicker.js.map +1 -1
  29. package/dist/components/TimePicker/types.d.ts +3 -3
  30. package/dist/components/TimePicker/utils.d.ts +13 -1
  31. package/dist/components/TimePicker.js +3 -2
  32. package/dist/components/TimePicker.js.map +1 -1
  33. package/dist/components/index.js +5 -4
  34. package/dist/components/index.js.map +1 -1
  35. package/dist/index.d.ts +2 -1
  36. package/dist/index.js +9 -239
  37. package/dist/index.js.map +1 -1
  38. package/dist/primitives/Calendar.js +8112 -8
  39. package/dist/primitives/Calendar.js.map +1 -1
  40. package/dist/primitives/index.js +1 -1
  41. package/dist/utils/inputMask.d.ts +38 -0
  42. package/dist/utils/timezone.d.ts +7 -0
  43. package/package.json +2 -1
  44. package/dist/Calendar-CjOBwDbx.js +0 -8134
  45. package/dist/Calendar-CjOBwDbx.js.map +0 -1
  46. package/dist/DatePicker-CCN3b1oz.js +0 -3166
  47. package/dist/DatePicker-CCN3b1oz.js.map +0 -1
  48. package/dist/TimePicker-wPi2k6Z8.js.map +0 -1
  49. package/dist/TimePickerPanel-DAhz3B2d.js +0 -227
  50. package/dist/TimePickerPanel-DAhz3B2d.js.map +0 -1
  51. package/dist/cjs/Calendar-02KiUZTT.js +0 -8175
  52. package/dist/cjs/Calendar-02KiUZTT.js.map +0 -1
  53. package/dist/cjs/DatePicker-DRQubO2h.js +0 -3168
  54. package/dist/cjs/DatePicker-DRQubO2h.js.map +0 -1
  55. package/dist/cjs/TimePicker-BG_vYH3r.js.map +0 -1
  56. package/dist/cjs/TimePickerPanel-6xA-hjhm.js +0 -233
  57. package/dist/cjs/TimePickerPanel-6xA-hjhm.js.map +0 -1
  58. package/dist/utils/dayjs/index.d.ts +0 -4
  59. package/dist/utils/dayjs/timezonePlugin.d.ts +0 -3
@@ -1,3166 +0,0 @@
1
- import { jsxs, jsx } from 'react/jsx-runtime';
2
- import { forwardRef, useId, useRef, useState, useCallback, useEffect } from 'react';
3
- import { g as getDefaultOptions$1, t as toDate, c as constructFrom, m as millisecondsInHour, b as millisecondsInMinute, d as millisecondsInSecond, e as getWeekYear, s as startOfWeek, f as startOfISOWeek, h as getWeek, i as getISOWeek, j as addDays, k as getTimezoneOffsetInMilliseconds, l as enUS, n as longFormatters, o as isProtectedWeekYearToken, w as warnOrThrowProtectedError, p as isProtectedDayOfYearToken, q as format, C as Calendar$1 } from './Calendar-CjOBwDbx.js';
4
- import { Popover, PopoverAnchor, PopoverContent } from './primitives/Popover.js';
5
- import { Field, FieldLabel, FieldContent, FieldError, FieldDescription } from './primitives/Field.js';
6
- import { c as cn } from './utils-BJnb9o5c.js';
7
- import { Button } from './primitives/Button.js';
8
- import { d as dateToTimeValue, T as TimePickerPanel } from './TimePickerPanel-DAhz3B2d.js';
9
- import { c as createLucideIcon } from './createLucideIcon-C8ycilSN.js';
10
- import { X } from './x-_o2T3n6D.js';
11
-
12
- /**
13
- * @license lucide-react v0.577.0 - ISC
14
- *
15
- * This source code is licensed under the ISC license.
16
- * See the LICENSE file in the root directory of this source tree.
17
- */
18
-
19
-
20
- const __iconNode = [
21
- ["path", { d: "M8 2v4", key: "1cmpym" }],
22
- ["path", { d: "M16 2v4", key: "4m81vk" }],
23
- ["rect", { width: "18", height: "18", x: "3", y: "4", rx: "2", key: "1hopcy" }],
24
- ["path", { d: "M3 10h18", key: "8toen8" }]
25
- ];
26
- const Calendar = createLucideIcon("calendar", __iconNode);
27
-
28
- /**
29
- * @name getDefaultOptions
30
- * @category Common Helpers
31
- * @summary Get default options.
32
- * @pure false
33
- *
34
- * @description
35
- * Returns an object that contains defaults for
36
- * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`
37
- * arguments for all functions.
38
- *
39
- * You can change these with [setDefaultOptions](https://date-fns.org/docs/setDefaultOptions).
40
- *
41
- * @returns The default options
42
- *
43
- * @example
44
- * const result = getDefaultOptions()
45
- * //=> {}
46
- *
47
- * @example
48
- * setDefaultOptions({ weekStarsOn: 1, firstWeekContainsDate: 4 })
49
- * const result = getDefaultOptions()
50
- * //=> { weekStarsOn: 1, firstWeekContainsDate: 4 }
51
- */
52
- function getDefaultOptions() {
53
- return Object.assign({}, getDefaultOptions$1());
54
- }
55
-
56
- /**
57
- * The {@link getISODay} function options.
58
- */
59
-
60
- /**
61
- * @name getISODay
62
- * @category Weekday Helpers
63
- * @summary Get the day of the ISO week of the given date.
64
- *
65
- * @description
66
- * Get the day of the ISO week of the given date,
67
- * which is 7 for Sunday, 1 for Monday etc.
68
- *
69
- * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
70
- *
71
- * @param date - The given date
72
- * @param options - An object with options
73
- *
74
- * @returns The day of ISO week
75
- *
76
- * @example
77
- * // Which day of the ISO week is 26 February 2012?
78
- * const result = getISODay(new Date(2012, 1, 26))
79
- * //=> 7
80
- */
81
- function getISODay(date, options) {
82
- const day = toDate(date, options?.in).getDay();
83
- return day === 0 ? 7 : day;
84
- }
85
-
86
- /**
87
- * @name transpose
88
- * @category Generic Helpers
89
- * @summary Transpose the date to the given constructor.
90
- *
91
- * @description
92
- * The function transposes the date to the given constructor. It helps you
93
- * to transpose the date in the system time zone to say `UTCDate` or any other
94
- * date extension.
95
- *
96
- * @typeParam InputDate - The input `Date` type derived from the passed argument.
97
- * @typeParam ResultDate - The result `Date` type derived from the passed constructor.
98
- *
99
- * @param date - The date to use values from
100
- * @param constructor - The date constructor to use
101
- *
102
- * @returns Date transposed to the given constructor
103
- *
104
- * @example
105
- * // Create July 10, 2022 00:00 in locale time zone
106
- * const date = new Date(2022, 6, 10)
107
- * //=> 'Sun Jul 10 2022 00:00:00 GMT+0800 (Singapore Standard Time)'
108
- *
109
- * @example
110
- * // Transpose the date to July 10, 2022 00:00 in UTC
111
- * transpose(date, UTCDate)
112
- * //=> 'Sun Jul 10 2022 00:00:00 GMT+0000 (Coordinated Universal Time)'
113
- */
114
- function transpose(date, constructor) {
115
- const date_ = isConstructor(constructor)
116
- ? new constructor(0)
117
- : constructFrom(constructor, 0);
118
- date_.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
119
- date_.setHours(
120
- date.getHours(),
121
- date.getMinutes(),
122
- date.getSeconds(),
123
- date.getMilliseconds(),
124
- );
125
- return date_;
126
- }
127
-
128
- function isConstructor(constructor) {
129
- return (
130
- typeof constructor === "function" &&
131
- constructor.prototype?.constructor === constructor
132
- );
133
- }
134
-
135
- const TIMEZONE_UNIT_PRIORITY = 10;
136
-
137
- class Setter {
138
- subPriority = 0;
139
-
140
- validate(_utcDate, _options) {
141
- return true;
142
- }
143
- }
144
-
145
- class ValueSetter extends Setter {
146
- constructor(
147
- value,
148
-
149
- validateValue,
150
-
151
- setValue,
152
-
153
- priority,
154
- subPriority,
155
- ) {
156
- super();
157
- this.value = value;
158
- this.validateValue = validateValue;
159
- this.setValue = setValue;
160
- this.priority = priority;
161
- if (subPriority) {
162
- this.subPriority = subPriority;
163
- }
164
- }
165
-
166
- validate(date, options) {
167
- return this.validateValue(date, this.value, options);
168
- }
169
-
170
- set(date, flags, options) {
171
- return this.setValue(date, flags, this.value, options);
172
- }
173
- }
174
-
175
- class DateTimezoneSetter extends Setter {
176
- priority = TIMEZONE_UNIT_PRIORITY;
177
- subPriority = -1;
178
-
179
- constructor(context, reference) {
180
- super();
181
- this.context = context || ((date) => constructFrom(reference, date));
182
- }
183
-
184
- set(date, flags) {
185
- if (flags.timestampIsSet) return date;
186
- return constructFrom(date, transpose(date, this.context));
187
- }
188
- }
189
-
190
- class Parser {
191
- run(dateString, token, match, options) {
192
- const result = this.parse(dateString, token, match, options);
193
- if (!result) {
194
- return null;
195
- }
196
-
197
- return {
198
- setter: new ValueSetter(
199
- result.value,
200
- this.validate,
201
- this.set,
202
- this.priority,
203
- this.subPriority,
204
- ),
205
- rest: result.rest,
206
- };
207
- }
208
-
209
- validate(_utcDate, _value, _options) {
210
- return true;
211
- }
212
- }
213
-
214
- class EraParser extends Parser {
215
- priority = 140;
216
-
217
- parse(dateString, token, match) {
218
- switch (token) {
219
- // AD, BC
220
- case "G":
221
- case "GG":
222
- case "GGG":
223
- return (
224
- match.era(dateString, { width: "abbreviated" }) ||
225
- match.era(dateString, { width: "narrow" })
226
- );
227
-
228
- // A, B
229
- case "GGGGG":
230
- return match.era(dateString, { width: "narrow" });
231
- // Anno Domini, Before Christ
232
- case "GGGG":
233
- default:
234
- return (
235
- match.era(dateString, { width: "wide" }) ||
236
- match.era(dateString, { width: "abbreviated" }) ||
237
- match.era(dateString, { width: "narrow" })
238
- );
239
- }
240
- }
241
-
242
- set(date, flags, value) {
243
- flags.era = value;
244
- date.setFullYear(value, 0, 1);
245
- date.setHours(0, 0, 0, 0);
246
- return date;
247
- }
248
-
249
- incompatibleTokens = ["R", "u", "t", "T"];
250
- }
251
-
252
- const numericPatterns = {
253
- month: /^(1[0-2]|0?\d)/, // 0 to 12
254
- date: /^(3[0-1]|[0-2]?\d)/, // 0 to 31
255
- dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, // 0 to 366
256
- week: /^(5[0-3]|[0-4]?\d)/, // 0 to 53
257
- hour23h: /^(2[0-3]|[0-1]?\d)/, // 0 to 23
258
- hour24h: /^(2[0-4]|[0-1]?\d)/, // 0 to 24
259
- hour11h: /^(1[0-1]|0?\d)/, // 0 to 11
260
- hour12h: /^(1[0-2]|0?\d)/, // 0 to 12
261
- minute: /^[0-5]?\d/, // 0 to 59
262
- second: /^[0-5]?\d/, // 0 to 59
263
-
264
- singleDigit: /^\d/, // 0 to 9
265
- twoDigits: /^\d{1,2}/, // 0 to 99
266
- threeDigits: /^\d{1,3}/, // 0 to 999
267
- fourDigits: /^\d{1,4}/, // 0 to 9999
268
-
269
- anyDigitsSigned: /^-?\d+/,
270
- singleDigitSigned: /^-?\d/, // 0 to 9, -0 to -9
271
- twoDigitsSigned: /^-?\d{1,2}/, // 0 to 99, -0 to -99
272
- threeDigitsSigned: /^-?\d{1,3}/, // 0 to 999, -0 to -999
273
- fourDigitsSigned: /^-?\d{1,4}/, // 0 to 9999, -0 to -9999
274
- };
275
-
276
- const timezonePatterns = {
277
- basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/,
278
- basic: /^([+-])(\d{2})(\d{2})|Z/,
279
- basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,
280
- extended: /^([+-])(\d{2}):(\d{2})|Z/,
281
- extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/,
282
- };
283
-
284
- function mapValue(parseFnResult, mapFn) {
285
- if (!parseFnResult) {
286
- return parseFnResult;
287
- }
288
-
289
- return {
290
- value: mapFn(parseFnResult.value),
291
- rest: parseFnResult.rest,
292
- };
293
- }
294
-
295
- function parseNumericPattern(pattern, dateString) {
296
- const matchResult = dateString.match(pattern);
297
-
298
- if (!matchResult) {
299
- return null;
300
- }
301
-
302
- return {
303
- value: parseInt(matchResult[0], 10),
304
- rest: dateString.slice(matchResult[0].length),
305
- };
306
- }
307
-
308
- function parseTimezonePattern(pattern, dateString) {
309
- const matchResult = dateString.match(pattern);
310
-
311
- if (!matchResult) {
312
- return null;
313
- }
314
-
315
- // Input is 'Z'
316
- if (matchResult[0] === "Z") {
317
- return {
318
- value: 0,
319
- rest: dateString.slice(1),
320
- };
321
- }
322
-
323
- const sign = matchResult[1] === "+" ? 1 : -1;
324
- const hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;
325
- const minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;
326
- const seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;
327
-
328
- return {
329
- value:
330
- sign *
331
- (hours * millisecondsInHour +
332
- minutes * millisecondsInMinute +
333
- seconds * millisecondsInSecond),
334
- rest: dateString.slice(matchResult[0].length),
335
- };
336
- }
337
-
338
- function parseAnyDigitsSigned(dateString) {
339
- return parseNumericPattern(numericPatterns.anyDigitsSigned, dateString);
340
- }
341
-
342
- function parseNDigits(n, dateString) {
343
- switch (n) {
344
- case 1:
345
- return parseNumericPattern(numericPatterns.singleDigit, dateString);
346
- case 2:
347
- return parseNumericPattern(numericPatterns.twoDigits, dateString);
348
- case 3:
349
- return parseNumericPattern(numericPatterns.threeDigits, dateString);
350
- case 4:
351
- return parseNumericPattern(numericPatterns.fourDigits, dateString);
352
- default:
353
- return parseNumericPattern(new RegExp("^\\d{1," + n + "}"), dateString);
354
- }
355
- }
356
-
357
- function parseNDigitsSigned(n, dateString) {
358
- switch (n) {
359
- case 1:
360
- return parseNumericPattern(numericPatterns.singleDigitSigned, dateString);
361
- case 2:
362
- return parseNumericPattern(numericPatterns.twoDigitsSigned, dateString);
363
- case 3:
364
- return parseNumericPattern(numericPatterns.threeDigitsSigned, dateString);
365
- case 4:
366
- return parseNumericPattern(numericPatterns.fourDigitsSigned, dateString);
367
- default:
368
- return parseNumericPattern(new RegExp("^-?\\d{1," + n + "}"), dateString);
369
- }
370
- }
371
-
372
- function dayPeriodEnumToHours(dayPeriod) {
373
- switch (dayPeriod) {
374
- case "morning":
375
- return 4;
376
- case "evening":
377
- return 17;
378
- case "pm":
379
- case "noon":
380
- case "afternoon":
381
- return 12;
382
- case "am":
383
- case "midnight":
384
- case "night":
385
- default:
386
- return 0;
387
- }
388
- }
389
-
390
- function normalizeTwoDigitYear(twoDigitYear, currentYear) {
391
- const isCommonEra = currentYear > 0;
392
- // Absolute number of the current year:
393
- // 1 -> 1 AC
394
- // 0 -> 1 BC
395
- // -1 -> 2 BC
396
- const absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;
397
-
398
- let result;
399
- if (absCurrentYear <= 50) {
400
- result = twoDigitYear || 100;
401
- } else {
402
- const rangeEnd = absCurrentYear + 50;
403
- const rangeEndCentury = Math.trunc(rangeEnd / 100) * 100;
404
- const isPreviousCentury = twoDigitYear >= rangeEnd % 100;
405
- result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);
406
- }
407
-
408
- return isCommonEra ? result : 1 - result;
409
- }
410
-
411
- function isLeapYearIndex(year) {
412
- return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
413
- }
414
-
415
- // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
416
- // | Year | y | yy | yyy | yyyy | yyyyy |
417
- // |----------|-------|----|-------|-------|-------|
418
- // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
419
- // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
420
- // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
421
- // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
422
- // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
423
- class YearParser extends Parser {
424
- priority = 130;
425
- incompatibleTokens = ["Y", "R", "u", "w", "I", "i", "e", "c", "t", "T"];
426
-
427
- parse(dateString, token, match) {
428
- const valueCallback = (year) => ({
429
- year,
430
- isTwoDigitYear: token === "yy",
431
- });
432
-
433
- switch (token) {
434
- case "y":
435
- return mapValue(parseNDigits(4, dateString), valueCallback);
436
- case "yo":
437
- return mapValue(
438
- match.ordinalNumber(dateString, {
439
- unit: "year",
440
- }),
441
- valueCallback,
442
- );
443
- default:
444
- return mapValue(parseNDigits(token.length, dateString), valueCallback);
445
- }
446
- }
447
-
448
- validate(_date, value) {
449
- return value.isTwoDigitYear || value.year > 0;
450
- }
451
-
452
- set(date, flags, value) {
453
- const currentYear = date.getFullYear();
454
-
455
- if (value.isTwoDigitYear) {
456
- const normalizedTwoDigitYear = normalizeTwoDigitYear(
457
- value.year,
458
- currentYear,
459
- );
460
- date.setFullYear(normalizedTwoDigitYear, 0, 1);
461
- date.setHours(0, 0, 0, 0);
462
- return date;
463
- }
464
-
465
- const year =
466
- !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
467
- date.setFullYear(year, 0, 1);
468
- date.setHours(0, 0, 0, 0);
469
- return date;
470
- }
471
- }
472
-
473
- // Local week-numbering year
474
- class LocalWeekYearParser extends Parser {
475
- priority = 130;
476
-
477
- parse(dateString, token, match) {
478
- const valueCallback = (year) => ({
479
- year,
480
- isTwoDigitYear: token === "YY",
481
- });
482
-
483
- switch (token) {
484
- case "Y":
485
- return mapValue(parseNDigits(4, dateString), valueCallback);
486
- case "Yo":
487
- return mapValue(
488
- match.ordinalNumber(dateString, {
489
- unit: "year",
490
- }),
491
- valueCallback,
492
- );
493
- default:
494
- return mapValue(parseNDigits(token.length, dateString), valueCallback);
495
- }
496
- }
497
-
498
- validate(_date, value) {
499
- return value.isTwoDigitYear || value.year > 0;
500
- }
501
-
502
- set(date, flags, value, options) {
503
- const currentYear = getWeekYear(date, options);
504
-
505
- if (value.isTwoDigitYear) {
506
- const normalizedTwoDigitYear = normalizeTwoDigitYear(
507
- value.year,
508
- currentYear,
509
- );
510
- date.setFullYear(
511
- normalizedTwoDigitYear,
512
- 0,
513
- options.firstWeekContainsDate,
514
- );
515
- date.setHours(0, 0, 0, 0);
516
- return startOfWeek(date, options);
517
- }
518
-
519
- const year =
520
- !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
521
- date.setFullYear(year, 0, options.firstWeekContainsDate);
522
- date.setHours(0, 0, 0, 0);
523
- return startOfWeek(date, options);
524
- }
525
-
526
- incompatibleTokens = [
527
- "y",
528
- "R",
529
- "u",
530
- "Q",
531
- "q",
532
- "M",
533
- "L",
534
- "I",
535
- "d",
536
- "D",
537
- "i",
538
- "t",
539
- "T",
540
- ];
541
- }
542
-
543
- // ISO week-numbering year
544
- class ISOWeekYearParser extends Parser {
545
- priority = 130;
546
-
547
- parse(dateString, token) {
548
- if (token === "R") {
549
- return parseNDigitsSigned(4, dateString);
550
- }
551
-
552
- return parseNDigitsSigned(token.length, dateString);
553
- }
554
-
555
- set(date, _flags, value) {
556
- const firstWeekOfYear = constructFrom(date, 0);
557
- firstWeekOfYear.setFullYear(value, 0, 4);
558
- firstWeekOfYear.setHours(0, 0, 0, 0);
559
- return startOfISOWeek(firstWeekOfYear);
560
- }
561
-
562
- incompatibleTokens = [
563
- "G",
564
- "y",
565
- "Y",
566
- "u",
567
- "Q",
568
- "q",
569
- "M",
570
- "L",
571
- "w",
572
- "d",
573
- "D",
574
- "e",
575
- "c",
576
- "t",
577
- "T",
578
- ];
579
- }
580
-
581
- class ExtendedYearParser extends Parser {
582
- priority = 130;
583
-
584
- parse(dateString, token) {
585
- if (token === "u") {
586
- return parseNDigitsSigned(4, dateString);
587
- }
588
-
589
- return parseNDigitsSigned(token.length, dateString);
590
- }
591
-
592
- set(date, _flags, value) {
593
- date.setFullYear(value, 0, 1);
594
- date.setHours(0, 0, 0, 0);
595
- return date;
596
- }
597
-
598
- incompatibleTokens = ["G", "y", "Y", "R", "w", "I", "i", "e", "c", "t", "T"];
599
- }
600
-
601
- class QuarterParser extends Parser {
602
- priority = 120;
603
-
604
- parse(dateString, token, match) {
605
- switch (token) {
606
- // 1, 2, 3, 4
607
- case "Q":
608
- case "QQ": // 01, 02, 03, 04
609
- return parseNDigits(token.length, dateString);
610
- // 1st, 2nd, 3rd, 4th
611
- case "Qo":
612
- return match.ordinalNumber(dateString, { unit: "quarter" });
613
- // Q1, Q2, Q3, Q4
614
- case "QQQ":
615
- return (
616
- match.quarter(dateString, {
617
- width: "abbreviated",
618
- context: "formatting",
619
- }) ||
620
- match.quarter(dateString, {
621
- width: "narrow",
622
- context: "formatting",
623
- })
624
- );
625
-
626
- // 1, 2, 3, 4 (narrow quarter; could be not numerical)
627
- case "QQQQQ":
628
- return match.quarter(dateString, {
629
- width: "narrow",
630
- context: "formatting",
631
- });
632
- // 1st quarter, 2nd quarter, ...
633
- case "QQQQ":
634
- default:
635
- return (
636
- match.quarter(dateString, {
637
- width: "wide",
638
- context: "formatting",
639
- }) ||
640
- match.quarter(dateString, {
641
- width: "abbreviated",
642
- context: "formatting",
643
- }) ||
644
- match.quarter(dateString, {
645
- width: "narrow",
646
- context: "formatting",
647
- })
648
- );
649
- }
650
- }
651
-
652
- validate(_date, value) {
653
- return value >= 1 && value <= 4;
654
- }
655
-
656
- set(date, _flags, value) {
657
- date.setMonth((value - 1) * 3, 1);
658
- date.setHours(0, 0, 0, 0);
659
- return date;
660
- }
661
-
662
- incompatibleTokens = [
663
- "Y",
664
- "R",
665
- "q",
666
- "M",
667
- "L",
668
- "w",
669
- "I",
670
- "d",
671
- "D",
672
- "i",
673
- "e",
674
- "c",
675
- "t",
676
- "T",
677
- ];
678
- }
679
-
680
- class StandAloneQuarterParser extends Parser {
681
- priority = 120;
682
-
683
- parse(dateString, token, match) {
684
- switch (token) {
685
- // 1, 2, 3, 4
686
- case "q":
687
- case "qq": // 01, 02, 03, 04
688
- return parseNDigits(token.length, dateString);
689
- // 1st, 2nd, 3rd, 4th
690
- case "qo":
691
- return match.ordinalNumber(dateString, { unit: "quarter" });
692
- // Q1, Q2, Q3, Q4
693
- case "qqq":
694
- return (
695
- match.quarter(dateString, {
696
- width: "abbreviated",
697
- context: "standalone",
698
- }) ||
699
- match.quarter(dateString, {
700
- width: "narrow",
701
- context: "standalone",
702
- })
703
- );
704
-
705
- // 1, 2, 3, 4 (narrow quarter; could be not numerical)
706
- case "qqqqq":
707
- return match.quarter(dateString, {
708
- width: "narrow",
709
- context: "standalone",
710
- });
711
- // 1st quarter, 2nd quarter, ...
712
- case "qqqq":
713
- default:
714
- return (
715
- match.quarter(dateString, {
716
- width: "wide",
717
- context: "standalone",
718
- }) ||
719
- match.quarter(dateString, {
720
- width: "abbreviated",
721
- context: "standalone",
722
- }) ||
723
- match.quarter(dateString, {
724
- width: "narrow",
725
- context: "standalone",
726
- })
727
- );
728
- }
729
- }
730
-
731
- validate(_date, value) {
732
- return value >= 1 && value <= 4;
733
- }
734
-
735
- set(date, _flags, value) {
736
- date.setMonth((value - 1) * 3, 1);
737
- date.setHours(0, 0, 0, 0);
738
- return date;
739
- }
740
-
741
- incompatibleTokens = [
742
- "Y",
743
- "R",
744
- "Q",
745
- "M",
746
- "L",
747
- "w",
748
- "I",
749
- "d",
750
- "D",
751
- "i",
752
- "e",
753
- "c",
754
- "t",
755
- "T",
756
- ];
757
- }
758
-
759
- class MonthParser extends Parser {
760
- incompatibleTokens = [
761
- "Y",
762
- "R",
763
- "q",
764
- "Q",
765
- "L",
766
- "w",
767
- "I",
768
- "D",
769
- "i",
770
- "e",
771
- "c",
772
- "t",
773
- "T",
774
- ];
775
-
776
- priority = 110;
777
-
778
- parse(dateString, token, match) {
779
- const valueCallback = (value) => value - 1;
780
-
781
- switch (token) {
782
- // 1, 2, ..., 12
783
- case "M":
784
- return mapValue(
785
- parseNumericPattern(numericPatterns.month, dateString),
786
- valueCallback,
787
- );
788
- // 01, 02, ..., 12
789
- case "MM":
790
- return mapValue(parseNDigits(2, dateString), valueCallback);
791
- // 1st, 2nd, ..., 12th
792
- case "Mo":
793
- return mapValue(
794
- match.ordinalNumber(dateString, {
795
- unit: "month",
796
- }),
797
- valueCallback,
798
- );
799
- // Jan, Feb, ..., Dec
800
- case "MMM":
801
- return (
802
- match.month(dateString, {
803
- width: "abbreviated",
804
- context: "formatting",
805
- }) ||
806
- match.month(dateString, { width: "narrow", context: "formatting" })
807
- );
808
-
809
- // J, F, ..., D
810
- case "MMMMM":
811
- return match.month(dateString, {
812
- width: "narrow",
813
- context: "formatting",
814
- });
815
- // January, February, ..., December
816
- case "MMMM":
817
- default:
818
- return (
819
- match.month(dateString, { width: "wide", context: "formatting" }) ||
820
- match.month(dateString, {
821
- width: "abbreviated",
822
- context: "formatting",
823
- }) ||
824
- match.month(dateString, { width: "narrow", context: "formatting" })
825
- );
826
- }
827
- }
828
-
829
- validate(_date, value) {
830
- return value >= 0 && value <= 11;
831
- }
832
-
833
- set(date, _flags, value) {
834
- date.setMonth(value, 1);
835
- date.setHours(0, 0, 0, 0);
836
- return date;
837
- }
838
- }
839
-
840
- class StandAloneMonthParser extends Parser {
841
- priority = 110;
842
-
843
- parse(dateString, token, match) {
844
- const valueCallback = (value) => value - 1;
845
-
846
- switch (token) {
847
- // 1, 2, ..., 12
848
- case "L":
849
- return mapValue(
850
- parseNumericPattern(numericPatterns.month, dateString),
851
- valueCallback,
852
- );
853
- // 01, 02, ..., 12
854
- case "LL":
855
- return mapValue(parseNDigits(2, dateString), valueCallback);
856
- // 1st, 2nd, ..., 12th
857
- case "Lo":
858
- return mapValue(
859
- match.ordinalNumber(dateString, {
860
- unit: "month",
861
- }),
862
- valueCallback,
863
- );
864
- // Jan, Feb, ..., Dec
865
- case "LLL":
866
- return (
867
- match.month(dateString, {
868
- width: "abbreviated",
869
- context: "standalone",
870
- }) ||
871
- match.month(dateString, { width: "narrow", context: "standalone" })
872
- );
873
-
874
- // J, F, ..., D
875
- case "LLLLL":
876
- return match.month(dateString, {
877
- width: "narrow",
878
- context: "standalone",
879
- });
880
- // January, February, ..., December
881
- case "LLLL":
882
- default:
883
- return (
884
- match.month(dateString, { width: "wide", context: "standalone" }) ||
885
- match.month(dateString, {
886
- width: "abbreviated",
887
- context: "standalone",
888
- }) ||
889
- match.month(dateString, { width: "narrow", context: "standalone" })
890
- );
891
- }
892
- }
893
-
894
- validate(_date, value) {
895
- return value >= 0 && value <= 11;
896
- }
897
-
898
- set(date, _flags, value) {
899
- date.setMonth(value, 1);
900
- date.setHours(0, 0, 0, 0);
901
- return date;
902
- }
903
-
904
- incompatibleTokens = [
905
- "Y",
906
- "R",
907
- "q",
908
- "Q",
909
- "M",
910
- "w",
911
- "I",
912
- "D",
913
- "i",
914
- "e",
915
- "c",
916
- "t",
917
- "T",
918
- ];
919
- }
920
-
921
- /**
922
- * The {@link setWeek} function options.
923
- */
924
-
925
- /**
926
- * @name setWeek
927
- * @category Week Helpers
928
- * @summary Set the local week to the given date.
929
- *
930
- * @description
931
- * Set the local week to the given date, saving the weekday number.
932
- * The exact calculation depends on the values of
933
- * `options.weekStartsOn` (which is the index of the first day of the week)
934
- * and `options.firstWeekContainsDate` (which is the day of January, which is always in
935
- * the first week of the week-numbering year)
936
- *
937
- * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
938
- *
939
- * @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).
940
- * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
941
- *
942
- * @param date - The date to be changed
943
- * @param week - The week of the new date
944
- * @param options - An object with options
945
- *
946
- * @returns The new date with the local week set
947
- *
948
- * @example
949
- * // Set the 1st week to 2 January 2005 with default options:
950
- * const result = setWeek(new Date(2005, 0, 2), 1)
951
- * //=> Sun Dec 26 2004 00:00:00
952
- *
953
- * @example
954
- * // Set the 1st week to 2 January 2005,
955
- * // if Monday is the first day of the week,
956
- * // and the first week of the year always contains 4 January:
957
- * const result = setWeek(new Date(2005, 0, 2), 1, {
958
- * weekStartsOn: 1,
959
- * firstWeekContainsDate: 4
960
- * })
961
- * //=> Sun Jan 4 2004 00:00:00
962
- */
963
- function setWeek(date, week, options) {
964
- const date_ = toDate(date, options?.in);
965
- const diff = getWeek(date_, options) - week;
966
- date_.setDate(date_.getDate() - diff * 7);
967
- return toDate(date_, options?.in);
968
- }
969
-
970
- // Local week of year
971
- class LocalWeekParser extends Parser {
972
- priority = 100;
973
-
974
- parse(dateString, token, match) {
975
- switch (token) {
976
- case "w":
977
- return parseNumericPattern(numericPatterns.week, dateString);
978
- case "wo":
979
- return match.ordinalNumber(dateString, { unit: "week" });
980
- default:
981
- return parseNDigits(token.length, dateString);
982
- }
983
- }
984
-
985
- validate(_date, value) {
986
- return value >= 1 && value <= 53;
987
- }
988
-
989
- set(date, _flags, value, options) {
990
- return startOfWeek(setWeek(date, value, options), options);
991
- }
992
-
993
- incompatibleTokens = [
994
- "y",
995
- "R",
996
- "u",
997
- "q",
998
- "Q",
999
- "M",
1000
- "L",
1001
- "I",
1002
- "d",
1003
- "D",
1004
- "i",
1005
- "t",
1006
- "T",
1007
- ];
1008
- }
1009
-
1010
- /**
1011
- * The {@link setISOWeek} function options.
1012
- */
1013
-
1014
- /**
1015
- * @name setISOWeek
1016
- * @category ISO Week Helpers
1017
- * @summary Set the ISO week to the given date.
1018
- *
1019
- * @description
1020
- * Set the ISO week to the given date, saving the weekday number.
1021
- *
1022
- * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
1023
- *
1024
- * @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).
1025
- * @typeParam ResultDate - The `Date` type of the context function.
1026
- *
1027
- * @param date - The date to be changed
1028
- * @param week - The ISO week of the new date
1029
- * @param options - An object with options
1030
- *
1031
- * @returns The new date with the ISO week set
1032
- *
1033
- * @example
1034
- * // Set the 53rd ISO week to 7 August 2004:
1035
- * const result = setISOWeek(new Date(2004, 7, 7), 53)
1036
- * //=> Sat Jan 01 2005 00:00:00
1037
- */
1038
- function setISOWeek(date, week, options) {
1039
- const _date = toDate(date, options?.in);
1040
- const diff = getISOWeek(_date, options) - week;
1041
- _date.setDate(_date.getDate() - diff * 7);
1042
- return _date;
1043
- }
1044
-
1045
- // ISO week of year
1046
- class ISOWeekParser extends Parser {
1047
- priority = 100;
1048
-
1049
- parse(dateString, token, match) {
1050
- switch (token) {
1051
- case "I":
1052
- return parseNumericPattern(numericPatterns.week, dateString);
1053
- case "Io":
1054
- return match.ordinalNumber(dateString, { unit: "week" });
1055
- default:
1056
- return parseNDigits(token.length, dateString);
1057
- }
1058
- }
1059
-
1060
- validate(_date, value) {
1061
- return value >= 1 && value <= 53;
1062
- }
1063
-
1064
- set(date, _flags, value) {
1065
- return startOfISOWeek(setISOWeek(date, value));
1066
- }
1067
-
1068
- incompatibleTokens = [
1069
- "y",
1070
- "Y",
1071
- "u",
1072
- "q",
1073
- "Q",
1074
- "M",
1075
- "L",
1076
- "w",
1077
- "d",
1078
- "D",
1079
- "e",
1080
- "c",
1081
- "t",
1082
- "T",
1083
- ];
1084
- }
1085
-
1086
- const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
1087
- const DAYS_IN_MONTH_LEAP_YEAR = [
1088
- 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
1089
- ];
1090
-
1091
- // Day of the month
1092
- class DateParser extends Parser {
1093
- priority = 90;
1094
- subPriority = 1;
1095
-
1096
- parse(dateString, token, match) {
1097
- switch (token) {
1098
- case "d":
1099
- return parseNumericPattern(numericPatterns.date, dateString);
1100
- case "do":
1101
- return match.ordinalNumber(dateString, { unit: "date" });
1102
- default:
1103
- return parseNDigits(token.length, dateString);
1104
- }
1105
- }
1106
-
1107
- validate(date, value) {
1108
- const year = date.getFullYear();
1109
- const isLeapYear = isLeapYearIndex(year);
1110
- const month = date.getMonth();
1111
- if (isLeapYear) {
1112
- return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];
1113
- } else {
1114
- return value >= 1 && value <= DAYS_IN_MONTH[month];
1115
- }
1116
- }
1117
-
1118
- set(date, _flags, value) {
1119
- date.setDate(value);
1120
- date.setHours(0, 0, 0, 0);
1121
- return date;
1122
- }
1123
-
1124
- incompatibleTokens = [
1125
- "Y",
1126
- "R",
1127
- "q",
1128
- "Q",
1129
- "w",
1130
- "I",
1131
- "D",
1132
- "i",
1133
- "e",
1134
- "c",
1135
- "t",
1136
- "T",
1137
- ];
1138
- }
1139
-
1140
- class DayOfYearParser extends Parser {
1141
- priority = 90;
1142
-
1143
- subpriority = 1;
1144
-
1145
- parse(dateString, token, match) {
1146
- switch (token) {
1147
- case "D":
1148
- case "DD":
1149
- return parseNumericPattern(numericPatterns.dayOfYear, dateString);
1150
- case "Do":
1151
- return match.ordinalNumber(dateString, { unit: "date" });
1152
- default:
1153
- return parseNDigits(token.length, dateString);
1154
- }
1155
- }
1156
-
1157
- validate(date, value) {
1158
- const year = date.getFullYear();
1159
- const isLeapYear = isLeapYearIndex(year);
1160
- if (isLeapYear) {
1161
- return value >= 1 && value <= 366;
1162
- } else {
1163
- return value >= 1 && value <= 365;
1164
- }
1165
- }
1166
-
1167
- set(date, _flags, value) {
1168
- date.setMonth(0, value);
1169
- date.setHours(0, 0, 0, 0);
1170
- return date;
1171
- }
1172
-
1173
- incompatibleTokens = [
1174
- "Y",
1175
- "R",
1176
- "q",
1177
- "Q",
1178
- "M",
1179
- "L",
1180
- "w",
1181
- "I",
1182
- "d",
1183
- "E",
1184
- "i",
1185
- "e",
1186
- "c",
1187
- "t",
1188
- "T",
1189
- ];
1190
- }
1191
-
1192
- /**
1193
- * The {@link setDay} function options.
1194
- */
1195
-
1196
- /**
1197
- * @name setDay
1198
- * @category Weekday Helpers
1199
- * @summary Set the day of the week to the given date.
1200
- *
1201
- * @description
1202
- * Set the day of the week to the given date.
1203
- *
1204
- * @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).
1205
- * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
1206
- *
1207
- * @param date - The date to be changed
1208
- * @param day - The day of the week of the new date
1209
- * @param options - An object with options.
1210
- *
1211
- * @returns The new date with the day of the week set
1212
- *
1213
- * @example
1214
- * // Set week day to Sunday, with the default weekStartsOn of Sunday:
1215
- * const result = setDay(new Date(2014, 8, 1), 0)
1216
- * //=> Sun Aug 31 2014 00:00:00
1217
- *
1218
- * @example
1219
- * // Set week day to Sunday, with a weekStartsOn of Monday:
1220
- * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })
1221
- * //=> Sun Sep 07 2014 00:00:00
1222
- */
1223
- function setDay(date, day, options) {
1224
- const defaultOptions = getDefaultOptions$1();
1225
- const weekStartsOn =
1226
- options?.weekStartsOn ??
1227
- options?.locale?.options?.weekStartsOn ??
1228
- defaultOptions.weekStartsOn ??
1229
- defaultOptions.locale?.options?.weekStartsOn ??
1230
- 0;
1231
-
1232
- const date_ = toDate(date, options?.in);
1233
- const currentDay = date_.getDay();
1234
-
1235
- const remainder = day % 7;
1236
- const dayIndex = (remainder + 7) % 7;
1237
-
1238
- const delta = 7 - weekStartsOn;
1239
- const diff =
1240
- day < 0 || day > 6
1241
- ? day - ((currentDay + delta) % 7)
1242
- : ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);
1243
- return addDays(date_, diff, options);
1244
- }
1245
-
1246
- // Day of week
1247
- class DayParser extends Parser {
1248
- priority = 90;
1249
-
1250
- parse(dateString, token, match) {
1251
- switch (token) {
1252
- // Tue
1253
- case "E":
1254
- case "EE":
1255
- case "EEE":
1256
- return (
1257
- match.day(dateString, {
1258
- width: "abbreviated",
1259
- context: "formatting",
1260
- }) ||
1261
- match.day(dateString, { width: "short", context: "formatting" }) ||
1262
- match.day(dateString, { width: "narrow", context: "formatting" })
1263
- );
1264
-
1265
- // T
1266
- case "EEEEE":
1267
- return match.day(dateString, {
1268
- width: "narrow",
1269
- context: "formatting",
1270
- });
1271
- // Tu
1272
- case "EEEEEE":
1273
- return (
1274
- match.day(dateString, { width: "short", context: "formatting" }) ||
1275
- match.day(dateString, { width: "narrow", context: "formatting" })
1276
- );
1277
-
1278
- // Tuesday
1279
- case "EEEE":
1280
- default:
1281
- return (
1282
- match.day(dateString, { width: "wide", context: "formatting" }) ||
1283
- match.day(dateString, {
1284
- width: "abbreviated",
1285
- context: "formatting",
1286
- }) ||
1287
- match.day(dateString, { width: "short", context: "formatting" }) ||
1288
- match.day(dateString, { width: "narrow", context: "formatting" })
1289
- );
1290
- }
1291
- }
1292
-
1293
- validate(_date, value) {
1294
- return value >= 0 && value <= 6;
1295
- }
1296
-
1297
- set(date, _flags, value, options) {
1298
- date = setDay(date, value, options);
1299
- date.setHours(0, 0, 0, 0);
1300
- return date;
1301
- }
1302
-
1303
- incompatibleTokens = ["D", "i", "e", "c", "t", "T"];
1304
- }
1305
-
1306
- // Local day of week
1307
- class LocalDayParser extends Parser {
1308
- priority = 90;
1309
- parse(dateString, token, match, options) {
1310
- const valueCallback = (value) => {
1311
- // We want here floor instead of trunc, so we get -7 for value 0 instead of 0
1312
- const wholeWeekDays = Math.floor((value - 1) / 7) * 7;
1313
- return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;
1314
- };
1315
-
1316
- switch (token) {
1317
- // 3
1318
- case "e":
1319
- case "ee": // 03
1320
- return mapValue(parseNDigits(token.length, dateString), valueCallback);
1321
- // 3rd
1322
- case "eo":
1323
- return mapValue(
1324
- match.ordinalNumber(dateString, {
1325
- unit: "day",
1326
- }),
1327
- valueCallback,
1328
- );
1329
- // Tue
1330
- case "eee":
1331
- return (
1332
- match.day(dateString, {
1333
- width: "abbreviated",
1334
- context: "formatting",
1335
- }) ||
1336
- match.day(dateString, { width: "short", context: "formatting" }) ||
1337
- match.day(dateString, { width: "narrow", context: "formatting" })
1338
- );
1339
-
1340
- // T
1341
- case "eeeee":
1342
- return match.day(dateString, {
1343
- width: "narrow",
1344
- context: "formatting",
1345
- });
1346
- // Tu
1347
- case "eeeeee":
1348
- return (
1349
- match.day(dateString, { width: "short", context: "formatting" }) ||
1350
- match.day(dateString, { width: "narrow", context: "formatting" })
1351
- );
1352
-
1353
- // Tuesday
1354
- case "eeee":
1355
- default:
1356
- return (
1357
- match.day(dateString, { width: "wide", context: "formatting" }) ||
1358
- match.day(dateString, {
1359
- width: "abbreviated",
1360
- context: "formatting",
1361
- }) ||
1362
- match.day(dateString, { width: "short", context: "formatting" }) ||
1363
- match.day(dateString, { width: "narrow", context: "formatting" })
1364
- );
1365
- }
1366
- }
1367
-
1368
- validate(_date, value) {
1369
- return value >= 0 && value <= 6;
1370
- }
1371
-
1372
- set(date, _flags, value, options) {
1373
- date = setDay(date, value, options);
1374
- date.setHours(0, 0, 0, 0);
1375
- return date;
1376
- }
1377
-
1378
- incompatibleTokens = [
1379
- "y",
1380
- "R",
1381
- "u",
1382
- "q",
1383
- "Q",
1384
- "M",
1385
- "L",
1386
- "I",
1387
- "d",
1388
- "D",
1389
- "E",
1390
- "i",
1391
- "c",
1392
- "t",
1393
- "T",
1394
- ];
1395
- }
1396
-
1397
- // Stand-alone local day of week
1398
- class StandAloneLocalDayParser extends Parser {
1399
- priority = 90;
1400
-
1401
- parse(dateString, token, match, options) {
1402
- const valueCallback = (value) => {
1403
- // We want here floor instead of trunc, so we get -7 for value 0 instead of 0
1404
- const wholeWeekDays = Math.floor((value - 1) / 7) * 7;
1405
- return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;
1406
- };
1407
-
1408
- switch (token) {
1409
- // 3
1410
- case "c":
1411
- case "cc": // 03
1412
- return mapValue(parseNDigits(token.length, dateString), valueCallback);
1413
- // 3rd
1414
- case "co":
1415
- return mapValue(
1416
- match.ordinalNumber(dateString, {
1417
- unit: "day",
1418
- }),
1419
- valueCallback,
1420
- );
1421
- // Tue
1422
- case "ccc":
1423
- return (
1424
- match.day(dateString, {
1425
- width: "abbreviated",
1426
- context: "standalone",
1427
- }) ||
1428
- match.day(dateString, { width: "short", context: "standalone" }) ||
1429
- match.day(dateString, { width: "narrow", context: "standalone" })
1430
- );
1431
-
1432
- // T
1433
- case "ccccc":
1434
- return match.day(dateString, {
1435
- width: "narrow",
1436
- context: "standalone",
1437
- });
1438
- // Tu
1439
- case "cccccc":
1440
- return (
1441
- match.day(dateString, { width: "short", context: "standalone" }) ||
1442
- match.day(dateString, { width: "narrow", context: "standalone" })
1443
- );
1444
-
1445
- // Tuesday
1446
- case "cccc":
1447
- default:
1448
- return (
1449
- match.day(dateString, { width: "wide", context: "standalone" }) ||
1450
- match.day(dateString, {
1451
- width: "abbreviated",
1452
- context: "standalone",
1453
- }) ||
1454
- match.day(dateString, { width: "short", context: "standalone" }) ||
1455
- match.day(dateString, { width: "narrow", context: "standalone" })
1456
- );
1457
- }
1458
- }
1459
-
1460
- validate(_date, value) {
1461
- return value >= 0 && value <= 6;
1462
- }
1463
-
1464
- set(date, _flags, value, options) {
1465
- date = setDay(date, value, options);
1466
- date.setHours(0, 0, 0, 0);
1467
- return date;
1468
- }
1469
-
1470
- incompatibleTokens = [
1471
- "y",
1472
- "R",
1473
- "u",
1474
- "q",
1475
- "Q",
1476
- "M",
1477
- "L",
1478
- "I",
1479
- "d",
1480
- "D",
1481
- "E",
1482
- "i",
1483
- "e",
1484
- "t",
1485
- "T",
1486
- ];
1487
- }
1488
-
1489
- /**
1490
- * The {@link setISODay} function options.
1491
- */
1492
-
1493
- /**
1494
- * @name setISODay
1495
- * @category Weekday Helpers
1496
- * @summary Set the day of the ISO week to the given date.
1497
- *
1498
- * @description
1499
- * Set the day of the ISO week to the given date.
1500
- * ISO week starts with Monday.
1501
- * 7 is the index of Sunday, 1 is the index of Monday, etc.
1502
- *
1503
- * @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).
1504
- * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
1505
- *
1506
- * @param date - The date to be changed
1507
- * @param day - The day of the ISO week of the new date
1508
- * @param options - An object with options
1509
- *
1510
- * @returns The new date with the day of the ISO week set
1511
- *
1512
- * @example
1513
- * // Set Sunday to 1 September 2014:
1514
- * const result = setISODay(new Date(2014, 8, 1), 7)
1515
- * //=> Sun Sep 07 2014 00:00:00
1516
- */
1517
- function setISODay(date, day, options) {
1518
- const date_ = toDate(date, options?.in);
1519
- const currentDay = getISODay(date_, options);
1520
- const diff = day - currentDay;
1521
- return addDays(date_, diff, options);
1522
- }
1523
-
1524
- // ISO day of week
1525
- class ISODayParser extends Parser {
1526
- priority = 90;
1527
-
1528
- parse(dateString, token, match) {
1529
- const valueCallback = (value) => {
1530
- if (value === 0) {
1531
- return 7;
1532
- }
1533
- return value;
1534
- };
1535
-
1536
- switch (token) {
1537
- // 2
1538
- case "i":
1539
- case "ii": // 02
1540
- return parseNDigits(token.length, dateString);
1541
- // 2nd
1542
- case "io":
1543
- return match.ordinalNumber(dateString, { unit: "day" });
1544
- // Tue
1545
- case "iii":
1546
- return mapValue(
1547
- match.day(dateString, {
1548
- width: "abbreviated",
1549
- context: "formatting",
1550
- }) ||
1551
- match.day(dateString, {
1552
- width: "short",
1553
- context: "formatting",
1554
- }) ||
1555
- match.day(dateString, {
1556
- width: "narrow",
1557
- context: "formatting",
1558
- }),
1559
- valueCallback,
1560
- );
1561
- // T
1562
- case "iiiii":
1563
- return mapValue(
1564
- match.day(dateString, {
1565
- width: "narrow",
1566
- context: "formatting",
1567
- }),
1568
- valueCallback,
1569
- );
1570
- // Tu
1571
- case "iiiiii":
1572
- return mapValue(
1573
- match.day(dateString, {
1574
- width: "short",
1575
- context: "formatting",
1576
- }) ||
1577
- match.day(dateString, {
1578
- width: "narrow",
1579
- context: "formatting",
1580
- }),
1581
- valueCallback,
1582
- );
1583
- // Tuesday
1584
- case "iiii":
1585
- default:
1586
- return mapValue(
1587
- match.day(dateString, {
1588
- width: "wide",
1589
- context: "formatting",
1590
- }) ||
1591
- match.day(dateString, {
1592
- width: "abbreviated",
1593
- context: "formatting",
1594
- }) ||
1595
- match.day(dateString, {
1596
- width: "short",
1597
- context: "formatting",
1598
- }) ||
1599
- match.day(dateString, {
1600
- width: "narrow",
1601
- context: "formatting",
1602
- }),
1603
- valueCallback,
1604
- );
1605
- }
1606
- }
1607
-
1608
- validate(_date, value) {
1609
- return value >= 1 && value <= 7;
1610
- }
1611
-
1612
- set(date, _flags, value) {
1613
- date = setISODay(date, value);
1614
- date.setHours(0, 0, 0, 0);
1615
- return date;
1616
- }
1617
-
1618
- incompatibleTokens = [
1619
- "y",
1620
- "Y",
1621
- "u",
1622
- "q",
1623
- "Q",
1624
- "M",
1625
- "L",
1626
- "w",
1627
- "d",
1628
- "D",
1629
- "E",
1630
- "e",
1631
- "c",
1632
- "t",
1633
- "T",
1634
- ];
1635
- }
1636
-
1637
- class AMPMParser extends Parser {
1638
- priority = 80;
1639
-
1640
- parse(dateString, token, match) {
1641
- switch (token) {
1642
- case "a":
1643
- case "aa":
1644
- case "aaa":
1645
- return (
1646
- match.dayPeriod(dateString, {
1647
- width: "abbreviated",
1648
- context: "formatting",
1649
- }) ||
1650
- match.dayPeriod(dateString, {
1651
- width: "narrow",
1652
- context: "formatting",
1653
- })
1654
- );
1655
-
1656
- case "aaaaa":
1657
- return match.dayPeriod(dateString, {
1658
- width: "narrow",
1659
- context: "formatting",
1660
- });
1661
- case "aaaa":
1662
- default:
1663
- return (
1664
- match.dayPeriod(dateString, {
1665
- width: "wide",
1666
- context: "formatting",
1667
- }) ||
1668
- match.dayPeriod(dateString, {
1669
- width: "abbreviated",
1670
- context: "formatting",
1671
- }) ||
1672
- match.dayPeriod(dateString, {
1673
- width: "narrow",
1674
- context: "formatting",
1675
- })
1676
- );
1677
- }
1678
- }
1679
-
1680
- set(date, _flags, value) {
1681
- date.setHours(dayPeriodEnumToHours(value), 0, 0, 0);
1682
- return date;
1683
- }
1684
-
1685
- incompatibleTokens = ["b", "B", "H", "k", "t", "T"];
1686
- }
1687
-
1688
- class AMPMMidnightParser extends Parser {
1689
- priority = 80;
1690
-
1691
- parse(dateString, token, match) {
1692
- switch (token) {
1693
- case "b":
1694
- case "bb":
1695
- case "bbb":
1696
- return (
1697
- match.dayPeriod(dateString, {
1698
- width: "abbreviated",
1699
- context: "formatting",
1700
- }) ||
1701
- match.dayPeriod(dateString, {
1702
- width: "narrow",
1703
- context: "formatting",
1704
- })
1705
- );
1706
-
1707
- case "bbbbb":
1708
- return match.dayPeriod(dateString, {
1709
- width: "narrow",
1710
- context: "formatting",
1711
- });
1712
- case "bbbb":
1713
- default:
1714
- return (
1715
- match.dayPeriod(dateString, {
1716
- width: "wide",
1717
- context: "formatting",
1718
- }) ||
1719
- match.dayPeriod(dateString, {
1720
- width: "abbreviated",
1721
- context: "formatting",
1722
- }) ||
1723
- match.dayPeriod(dateString, {
1724
- width: "narrow",
1725
- context: "formatting",
1726
- })
1727
- );
1728
- }
1729
- }
1730
-
1731
- set(date, _flags, value) {
1732
- date.setHours(dayPeriodEnumToHours(value), 0, 0, 0);
1733
- return date;
1734
- }
1735
-
1736
- incompatibleTokens = ["a", "B", "H", "k", "t", "T"];
1737
- }
1738
-
1739
- // in the morning, in the afternoon, in the evening, at night
1740
- class DayPeriodParser extends Parser {
1741
- priority = 80;
1742
-
1743
- parse(dateString, token, match) {
1744
- switch (token) {
1745
- case "B":
1746
- case "BB":
1747
- case "BBB":
1748
- return (
1749
- match.dayPeriod(dateString, {
1750
- width: "abbreviated",
1751
- context: "formatting",
1752
- }) ||
1753
- match.dayPeriod(dateString, {
1754
- width: "narrow",
1755
- context: "formatting",
1756
- })
1757
- );
1758
-
1759
- case "BBBBB":
1760
- return match.dayPeriod(dateString, {
1761
- width: "narrow",
1762
- context: "formatting",
1763
- });
1764
- case "BBBB":
1765
- default:
1766
- return (
1767
- match.dayPeriod(dateString, {
1768
- width: "wide",
1769
- context: "formatting",
1770
- }) ||
1771
- match.dayPeriod(dateString, {
1772
- width: "abbreviated",
1773
- context: "formatting",
1774
- }) ||
1775
- match.dayPeriod(dateString, {
1776
- width: "narrow",
1777
- context: "formatting",
1778
- })
1779
- );
1780
- }
1781
- }
1782
-
1783
- set(date, _flags, value) {
1784
- date.setHours(dayPeriodEnumToHours(value), 0, 0, 0);
1785
- return date;
1786
- }
1787
-
1788
- incompatibleTokens = ["a", "b", "t", "T"];
1789
- }
1790
-
1791
- class Hour1to12Parser extends Parser {
1792
- priority = 70;
1793
-
1794
- parse(dateString, token, match) {
1795
- switch (token) {
1796
- case "h":
1797
- return parseNumericPattern(numericPatterns.hour12h, dateString);
1798
- case "ho":
1799
- return match.ordinalNumber(dateString, { unit: "hour" });
1800
- default:
1801
- return parseNDigits(token.length, dateString);
1802
- }
1803
- }
1804
-
1805
- validate(_date, value) {
1806
- return value >= 1 && value <= 12;
1807
- }
1808
-
1809
- set(date, _flags, value) {
1810
- const isPM = date.getHours() >= 12;
1811
- if (isPM && value < 12) {
1812
- date.setHours(value + 12, 0, 0, 0);
1813
- } else if (!isPM && value === 12) {
1814
- date.setHours(0, 0, 0, 0);
1815
- } else {
1816
- date.setHours(value, 0, 0, 0);
1817
- }
1818
- return date;
1819
- }
1820
-
1821
- incompatibleTokens = ["H", "K", "k", "t", "T"];
1822
- }
1823
-
1824
- class Hour0to23Parser extends Parser {
1825
- priority = 70;
1826
-
1827
- parse(dateString, token, match) {
1828
- switch (token) {
1829
- case "H":
1830
- return parseNumericPattern(numericPatterns.hour23h, dateString);
1831
- case "Ho":
1832
- return match.ordinalNumber(dateString, { unit: "hour" });
1833
- default:
1834
- return parseNDigits(token.length, dateString);
1835
- }
1836
- }
1837
-
1838
- validate(_date, value) {
1839
- return value >= 0 && value <= 23;
1840
- }
1841
-
1842
- set(date, _flags, value) {
1843
- date.setHours(value, 0, 0, 0);
1844
- return date;
1845
- }
1846
-
1847
- incompatibleTokens = ["a", "b", "h", "K", "k", "t", "T"];
1848
- }
1849
-
1850
- class Hour0To11Parser extends Parser {
1851
- priority = 70;
1852
-
1853
- parse(dateString, token, match) {
1854
- switch (token) {
1855
- case "K":
1856
- return parseNumericPattern(numericPatterns.hour11h, dateString);
1857
- case "Ko":
1858
- return match.ordinalNumber(dateString, { unit: "hour" });
1859
- default:
1860
- return parseNDigits(token.length, dateString);
1861
- }
1862
- }
1863
-
1864
- validate(_date, value) {
1865
- return value >= 0 && value <= 11;
1866
- }
1867
-
1868
- set(date, _flags, value) {
1869
- const isPM = date.getHours() >= 12;
1870
- if (isPM && value < 12) {
1871
- date.setHours(value + 12, 0, 0, 0);
1872
- } else {
1873
- date.setHours(value, 0, 0, 0);
1874
- }
1875
- return date;
1876
- }
1877
-
1878
- incompatibleTokens = ["h", "H", "k", "t", "T"];
1879
- }
1880
-
1881
- class Hour1To24Parser extends Parser {
1882
- priority = 70;
1883
-
1884
- parse(dateString, token, match) {
1885
- switch (token) {
1886
- case "k":
1887
- return parseNumericPattern(numericPatterns.hour24h, dateString);
1888
- case "ko":
1889
- return match.ordinalNumber(dateString, { unit: "hour" });
1890
- default:
1891
- return parseNDigits(token.length, dateString);
1892
- }
1893
- }
1894
-
1895
- validate(_date, value) {
1896
- return value >= 1 && value <= 24;
1897
- }
1898
-
1899
- set(date, _flags, value) {
1900
- const hours = value <= 24 ? value % 24 : value;
1901
- date.setHours(hours, 0, 0, 0);
1902
- return date;
1903
- }
1904
-
1905
- incompatibleTokens = ["a", "b", "h", "H", "K", "t", "T"];
1906
- }
1907
-
1908
- class MinuteParser extends Parser {
1909
- priority = 60;
1910
-
1911
- parse(dateString, token, match) {
1912
- switch (token) {
1913
- case "m":
1914
- return parseNumericPattern(numericPatterns.minute, dateString);
1915
- case "mo":
1916
- return match.ordinalNumber(dateString, { unit: "minute" });
1917
- default:
1918
- return parseNDigits(token.length, dateString);
1919
- }
1920
- }
1921
-
1922
- validate(_date, value) {
1923
- return value >= 0 && value <= 59;
1924
- }
1925
-
1926
- set(date, _flags, value) {
1927
- date.setMinutes(value, 0, 0);
1928
- return date;
1929
- }
1930
-
1931
- incompatibleTokens = ["t", "T"];
1932
- }
1933
-
1934
- class SecondParser extends Parser {
1935
- priority = 50;
1936
-
1937
- parse(dateString, token, match) {
1938
- switch (token) {
1939
- case "s":
1940
- return parseNumericPattern(numericPatterns.second, dateString);
1941
- case "so":
1942
- return match.ordinalNumber(dateString, { unit: "second" });
1943
- default:
1944
- return parseNDigits(token.length, dateString);
1945
- }
1946
- }
1947
-
1948
- validate(_date, value) {
1949
- return value >= 0 && value <= 59;
1950
- }
1951
-
1952
- set(date, _flags, value) {
1953
- date.setSeconds(value, 0);
1954
- return date;
1955
- }
1956
-
1957
- incompatibleTokens = ["t", "T"];
1958
- }
1959
-
1960
- class FractionOfSecondParser extends Parser {
1961
- priority = 30;
1962
-
1963
- parse(dateString, token) {
1964
- const valueCallback = (value) =>
1965
- Math.trunc(value * Math.pow(10, -token.length + 3));
1966
- return mapValue(parseNDigits(token.length, dateString), valueCallback);
1967
- }
1968
-
1969
- set(date, _flags, value) {
1970
- date.setMilliseconds(value);
1971
- return date;
1972
- }
1973
-
1974
- incompatibleTokens = ["t", "T"];
1975
- }
1976
-
1977
- // Timezone (ISO-8601. +00:00 is `'Z'`)
1978
- class ISOTimezoneWithZParser extends Parser {
1979
- priority = 10;
1980
-
1981
- parse(dateString, token) {
1982
- switch (token) {
1983
- case "X":
1984
- return parseTimezonePattern(
1985
- timezonePatterns.basicOptionalMinutes,
1986
- dateString,
1987
- );
1988
- case "XX":
1989
- return parseTimezonePattern(timezonePatterns.basic, dateString);
1990
- case "XXXX":
1991
- return parseTimezonePattern(
1992
- timezonePatterns.basicOptionalSeconds,
1993
- dateString,
1994
- );
1995
- case "XXXXX":
1996
- return parseTimezonePattern(
1997
- timezonePatterns.extendedOptionalSeconds,
1998
- dateString,
1999
- );
2000
- case "XXX":
2001
- default:
2002
- return parseTimezonePattern(timezonePatterns.extended, dateString);
2003
- }
2004
- }
2005
-
2006
- set(date, flags, value) {
2007
- if (flags.timestampIsSet) return date;
2008
- return constructFrom(
2009
- date,
2010
- date.getTime() - getTimezoneOffsetInMilliseconds(date) - value,
2011
- );
2012
- }
2013
-
2014
- incompatibleTokens = ["t", "T", "x"];
2015
- }
2016
-
2017
- // Timezone (ISO-8601)
2018
- class ISOTimezoneParser extends Parser {
2019
- priority = 10;
2020
-
2021
- parse(dateString, token) {
2022
- switch (token) {
2023
- case "x":
2024
- return parseTimezonePattern(
2025
- timezonePatterns.basicOptionalMinutes,
2026
- dateString,
2027
- );
2028
- case "xx":
2029
- return parseTimezonePattern(timezonePatterns.basic, dateString);
2030
- case "xxxx":
2031
- return parseTimezonePattern(
2032
- timezonePatterns.basicOptionalSeconds,
2033
- dateString,
2034
- );
2035
- case "xxxxx":
2036
- return parseTimezonePattern(
2037
- timezonePatterns.extendedOptionalSeconds,
2038
- dateString,
2039
- );
2040
- case "xxx":
2041
- default:
2042
- return parseTimezonePattern(timezonePatterns.extended, dateString);
2043
- }
2044
- }
2045
-
2046
- set(date, flags, value) {
2047
- if (flags.timestampIsSet) return date;
2048
- return constructFrom(
2049
- date,
2050
- date.getTime() - getTimezoneOffsetInMilliseconds(date) - value,
2051
- );
2052
- }
2053
-
2054
- incompatibleTokens = ["t", "T", "X"];
2055
- }
2056
-
2057
- class TimestampSecondsParser extends Parser {
2058
- priority = 40;
2059
-
2060
- parse(dateString) {
2061
- return parseAnyDigitsSigned(dateString);
2062
- }
2063
-
2064
- set(date, _flags, value) {
2065
- return [constructFrom(date, value * 1000), { timestampIsSet: true }];
2066
- }
2067
-
2068
- incompatibleTokens = "*";
2069
- }
2070
-
2071
- class TimestampMillisecondsParser extends Parser {
2072
- priority = 20;
2073
-
2074
- parse(dateString) {
2075
- return parseAnyDigitsSigned(dateString);
2076
- }
2077
-
2078
- set(date, _flags, value) {
2079
- return [constructFrom(date, value), { timestampIsSet: true }];
2080
- }
2081
-
2082
- incompatibleTokens = "*";
2083
- }
2084
-
2085
- /*
2086
- * | | Unit | | Unit |
2087
- * |-----|--------------------------------|-----|--------------------------------|
2088
- * | a | AM, PM | A* | Milliseconds in day |
2089
- * | b | AM, PM, noon, midnight | B | Flexible day period |
2090
- * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
2091
- * | d | Day of month | D | Day of year |
2092
- * | e | Local day of week | E | Day of week |
2093
- * | f | | F* | Day of week in month |
2094
- * | g* | Modified Julian day | G | Era |
2095
- * | h | Hour [1-12] | H | Hour [0-23] |
2096
- * | i! | ISO day of week | I! | ISO week of year |
2097
- * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
2098
- * | k | Hour [1-24] | K | Hour [0-11] |
2099
- * | l* | (deprecated) | L | Stand-alone month |
2100
- * | m | Minute | M | Month |
2101
- * | n | | N | |
2102
- * | o! | Ordinal number modifier | O* | Timezone (GMT) |
2103
- * | p | | P | |
2104
- * | q | Stand-alone quarter | Q | Quarter |
2105
- * | r* | Related Gregorian year | R! | ISO week-numbering year |
2106
- * | s | Second | S | Fraction of second |
2107
- * | t! | Seconds timestamp | T! | Milliseconds timestamp |
2108
- * | u | Extended year | U* | Cyclic year |
2109
- * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
2110
- * | w | Local week of year | W* | Week of month |
2111
- * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
2112
- * | y | Year (abs) | Y | Local week-numbering year |
2113
- * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
2114
- *
2115
- * Letters marked by * are not implemented but reserved by Unicode standard.
2116
- *
2117
- * Letters marked by ! are non-standard, but implemented by date-fns:
2118
- * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs)
2119
- * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
2120
- * i.e. 7 for Sunday, 1 for Monday, etc.
2121
- * - `I` is ISO week of year, as opposed to `w` which is local week of year.
2122
- * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
2123
- * `R` is supposed to be used in conjunction with `I` and `i`
2124
- * for universal ISO week-numbering date, whereas
2125
- * `Y` is supposed to be used in conjunction with `w` and `e`
2126
- * for week-numbering date specific to the locale.
2127
- */
2128
- const parsers = {
2129
- G: new EraParser(),
2130
- y: new YearParser(),
2131
- Y: new LocalWeekYearParser(),
2132
- R: new ISOWeekYearParser(),
2133
- u: new ExtendedYearParser(),
2134
- Q: new QuarterParser(),
2135
- q: new StandAloneQuarterParser(),
2136
- M: new MonthParser(),
2137
- L: new StandAloneMonthParser(),
2138
- w: new LocalWeekParser(),
2139
- I: new ISOWeekParser(),
2140
- d: new DateParser(),
2141
- D: new DayOfYearParser(),
2142
- E: new DayParser(),
2143
- e: new LocalDayParser(),
2144
- c: new StandAloneLocalDayParser(),
2145
- i: new ISODayParser(),
2146
- a: new AMPMParser(),
2147
- b: new AMPMMidnightParser(),
2148
- B: new DayPeriodParser(),
2149
- h: new Hour1to12Parser(),
2150
- H: new Hour0to23Parser(),
2151
- K: new Hour0To11Parser(),
2152
- k: new Hour1To24Parser(),
2153
- m: new MinuteParser(),
2154
- s: new SecondParser(),
2155
- S: new FractionOfSecondParser(),
2156
- X: new ISOTimezoneWithZParser(),
2157
- x: new ISOTimezoneParser(),
2158
- t: new TimestampSecondsParser(),
2159
- T: new TimestampMillisecondsParser(),
2160
- };
2161
-
2162
- /**
2163
- * The {@link parse} function options.
2164
- */
2165
-
2166
- // This RegExp consists of three parts separated by `|`:
2167
- // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
2168
- // (one of the certain letters followed by `o`)
2169
- // - (\w)\1* matches any sequences of the same letter
2170
- // - '' matches two quote characters in a row
2171
- // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
2172
- // except a single quote symbol, which ends the sequence.
2173
- // Two quote characters do not end the sequence.
2174
- // If there is no matching single quote
2175
- // then the sequence will continue until the end of the string.
2176
- // - . matches any single character unmatched by previous parts of the RegExps
2177
- const formattingTokensRegExp =
2178
- /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
2179
-
2180
- // This RegExp catches symbols escaped by quotes, and also
2181
- // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
2182
- const longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
2183
-
2184
- const escapedStringRegExp = /^'([^]*?)'?$/;
2185
- const doubleQuoteRegExp = /''/g;
2186
-
2187
- const notWhitespaceRegExp = /\S/;
2188
- const unescapedLatinCharacterRegExp = /[a-zA-Z]/;
2189
-
2190
- /**
2191
- * @name parse
2192
- * @category Common Helpers
2193
- * @summary Parse the date.
2194
- *
2195
- * @description
2196
- * Return the date parsed from string using the given format string.
2197
- *
2198
- * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
2199
- * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2200
- *
2201
- * The characters in the format string wrapped between two single quotes characters (') are escaped.
2202
- * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
2203
- *
2204
- * Format of the format string is based on Unicode Technical Standard #35:
2205
- * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
2206
- * with a few additions (see note 5 below the table).
2207
- *
2208
- * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited
2209
- * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:
2210
- *
2211
- * ```javascript
2212
- * parse('23 AM', 'HH a', new Date())
2213
- * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time
2214
- * ```
2215
- *
2216
- * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true
2217
- *
2218
- * Accepted format string patterns:
2219
- * | Unit |Prior| Pattern | Result examples | Notes |
2220
- * |---------------------------------|-----|---------|-----------------------------------|-------|
2221
- * | Era | 140 | G..GGG | AD, BC | |
2222
- * | | | GGGG | Anno Domini, Before Christ | 2 |
2223
- * | | | GGGGG | A, B | |
2224
- * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |
2225
- * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |
2226
- * | | | yy | 44, 01, 00, 17 | 4 |
2227
- * | | | yyy | 044, 001, 123, 999 | 4 |
2228
- * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |
2229
- * | | | yyyyy | ... | 2,4 |
2230
- * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |
2231
- * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |
2232
- * | | | YY | 44, 01, 00, 17 | 4,6 |
2233
- * | | | YYY | 044, 001, 123, 999 | 4 |
2234
- * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |
2235
- * | | | YYYYY | ... | 2,4 |
2236
- * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |
2237
- * | | | RR | -43, 01, 00, 17 | 4,5 |
2238
- * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |
2239
- * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |
2240
- * | | | RRRRR | ... | 2,4,5 |
2241
- * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |
2242
- * | | | uu | -43, 01, 99, -99 | 4 |
2243
- * | | | uuu | -043, 001, 123, 999, -999 | 4 |
2244
- * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |
2245
- * | | | uuuuu | ... | 2,4 |
2246
- * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |
2247
- * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |
2248
- * | | | QQ | 01, 02, 03, 04 | |
2249
- * | | | QQQ | Q1, Q2, Q3, Q4 | |
2250
- * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
2251
- * | | | QQQQQ | 1, 2, 3, 4 | 4 |
2252
- * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |
2253
- * | | | qo | 1st, 2nd, 3rd, 4th | 5 |
2254
- * | | | qq | 01, 02, 03, 04 | |
2255
- * | | | qqq | Q1, Q2, Q3, Q4 | |
2256
- * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
2257
- * | | | qqqqq | 1, 2, 3, 4 | 3 |
2258
- * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |
2259
- * | | | Mo | 1st, 2nd, ..., 12th | 5 |
2260
- * | | | MM | 01, 02, ..., 12 | |
2261
- * | | | MMM | Jan, Feb, ..., Dec | |
2262
- * | | | MMMM | January, February, ..., December | 2 |
2263
- * | | | MMMMM | J, F, ..., D | |
2264
- * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |
2265
- * | | | Lo | 1st, 2nd, ..., 12th | 5 |
2266
- * | | | LL | 01, 02, ..., 12 | |
2267
- * | | | LLL | Jan, Feb, ..., Dec | |
2268
- * | | | LLLL | January, February, ..., December | 2 |
2269
- * | | | LLLLL | J, F, ..., D | |
2270
- * | Local week of year | 100 | w | 1, 2, ..., 53 | |
2271
- * | | | wo | 1st, 2nd, ..., 53th | 5 |
2272
- * | | | ww | 01, 02, ..., 53 | |
2273
- * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |
2274
- * | | | Io | 1st, 2nd, ..., 53th | 5 |
2275
- * | | | II | 01, 02, ..., 53 | 5 |
2276
- * | Day of month | 90 | d | 1, 2, ..., 31 | |
2277
- * | | | do | 1st, 2nd, ..., 31st | 5 |
2278
- * | | | dd | 01, 02, ..., 31 | |
2279
- * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |
2280
- * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |
2281
- * | | | DD | 01, 02, ..., 365, 366 | 7 |
2282
- * | | | DDD | 001, 002, ..., 365, 366 | |
2283
- * | | | DDDD | ... | 2 |
2284
- * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | |
2285
- * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
2286
- * | | | EEEEE | M, T, W, T, F, S, S | |
2287
- * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
2288
- * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |
2289
- * | | | io | 1st, 2nd, ..., 7th | 5 |
2290
- * | | | ii | 01, 02, ..., 07 | 5 |
2291
- * | | | iii | Mon, Tue, Wed, ..., Sun | 5 |
2292
- * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |
2293
- * | | | iiiii | M, T, W, T, F, S, S | 5 |
2294
- * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |
2295
- * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |
2296
- * | | | eo | 2nd, 3rd, ..., 1st | 5 |
2297
- * | | | ee | 02, 03, ..., 01 | |
2298
- * | | | eee | Mon, Tue, Wed, ..., Sun | |
2299
- * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |
2300
- * | | | eeeee | M, T, W, T, F, S, S | |
2301
- * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
2302
- * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |
2303
- * | | | co | 2nd, 3rd, ..., 1st | 5 |
2304
- * | | | cc | 02, 03, ..., 01 | |
2305
- * | | | ccc | Mon, Tue, Wed, ..., Sun | |
2306
- * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |
2307
- * | | | ccccc | M, T, W, T, F, S, S | |
2308
- * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
2309
- * | AM, PM | 80 | a..aaa | AM, PM | |
2310
- * | | | aaaa | a.m., p.m. | 2 |
2311
- * | | | aaaaa | a, p | |
2312
- * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |
2313
- * | | | bbbb | a.m., p.m., noon, midnight | 2 |
2314
- * | | | bbbbb | a, p, n, mi | |
2315
- * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |
2316
- * | | | BBBB | at night, in the morning, ... | 2 |
2317
- * | | | BBBBB | at night, in the morning, ... | |
2318
- * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |
2319
- * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |
2320
- * | | | hh | 01, 02, ..., 11, 12 | |
2321
- * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |
2322
- * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |
2323
- * | | | HH | 00, 01, 02, ..., 23 | |
2324
- * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |
2325
- * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |
2326
- * | | | KK | 01, 02, ..., 11, 00 | |
2327
- * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |
2328
- * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |
2329
- * | | | kk | 24, 01, 02, ..., 23 | |
2330
- * | Minute | 60 | m | 0, 1, ..., 59 | |
2331
- * | | | mo | 0th, 1st, ..., 59th | 5 |
2332
- * | | | mm | 00, 01, ..., 59 | |
2333
- * | Second | 50 | s | 0, 1, ..., 59 | |
2334
- * | | | so | 0th, 1st, ..., 59th | 5 |
2335
- * | | | ss | 00, 01, ..., 59 | |
2336
- * | Seconds timestamp | 40 | t | 512969520 | |
2337
- * | | | tt | ... | 2 |
2338
- * | Fraction of second | 30 | S | 0, 1, ..., 9 | |
2339
- * | | | SS | 00, 01, ..., 99 | |
2340
- * | | | SSS | 000, 001, ..., 999 | |
2341
- * | | | SSSS | ... | 2 |
2342
- * | Milliseconds timestamp | 20 | T | 512969520900 | |
2343
- * | | | TT | ... | 2 |
2344
- * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |
2345
- * | | | XX | -0800, +0530, Z | |
2346
- * | | | XXX | -08:00, +05:30, Z | |
2347
- * | | | XXXX | -0800, +0530, Z, +123456 | 2 |
2348
- * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
2349
- * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |
2350
- * | | | xx | -0800, +0530, +0000 | |
2351
- * | | | xxx | -08:00, +05:30, +00:00 | 2 |
2352
- * | | | xxxx | -0800, +0530, +0000, +123456 | |
2353
- * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
2354
- * | Long localized date | NA | P | 05/29/1453 | 5,8 |
2355
- * | | | PP | May 29, 1453 | |
2356
- * | | | PPP | May 29th, 1453 | |
2357
- * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |
2358
- * | Long localized time | NA | p | 12:00 AM | 5,8 |
2359
- * | | | pp | 12:00:00 AM | |
2360
- * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |
2361
- * | | | PPpp | May 29, 1453, 12:00:00 AM | |
2362
- * | | | PPPpp | May 29th, 1453 at ... | |
2363
- * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |
2364
- * Notes:
2365
- * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
2366
- * are the same as "stand-alone" units, but are different in some languages.
2367
- * "Formatting" units are declined according to the rules of the language
2368
- * in the context of a date. "Stand-alone" units are always nominative singular.
2369
- * In `format` function, they will produce different result:
2370
- *
2371
- * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2372
- *
2373
- * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2374
- *
2375
- * `parse` will try to match both formatting and stand-alone units interchangeably.
2376
- *
2377
- * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2378
- * the single quote characters (see below).
2379
- * If the sequence is longer than listed in table:
2380
- * - for numerical units (`yyyyyyyy`) `parse` will try to match a number
2381
- * as wide as the sequence
2382
- * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit.
2383
- * These variations are marked with "2" in the last column of the table.
2384
- *
2385
- * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2386
- * These tokens represent the shortest form of the quarter.
2387
- *
2388
- * 4. The main difference between `y` and `u` patterns are B.C. years:
2389
- *
2390
- * | Year | `y` | `u` |
2391
- * |------|-----|-----|
2392
- * | AC 1 | 1 | 1 |
2393
- * | BC 1 | 1 | 0 |
2394
- * | BC 2 | 2 | -1 |
2395
- *
2396
- * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:
2397
- *
2398
- * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00`
2399
- *
2400
- * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00`
2401
- *
2402
- * while `uu` will just assign the year as is:
2403
- *
2404
- * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00`
2405
- *
2406
- * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00`
2407
- *
2408
- * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2409
- * except local week-numbering years are dependent on `options.weekStartsOn`
2410
- * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)
2411
- * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).
2412
- *
2413
- * 5. These patterns are not in the Unicode Technical Standard #35:
2414
- * - `i`: ISO day of week
2415
- * - `I`: ISO week of year
2416
- * - `R`: ISO week-numbering year
2417
- * - `o`: ordinal number modifier
2418
- * - `P`: long localized date
2419
- * - `p`: long localized time
2420
- *
2421
- * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2422
- * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2423
- *
2424
- * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2425
- * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2426
- *
2427
- * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based
2428
- * on the given locale.
2429
- *
2430
- * using `en-US` locale: `P` => `MM/dd/yyyy`
2431
- * using `en-US` locale: `p` => `hh:mm a`
2432
- * using `pt-BR` locale: `P` => `dd/MM/yyyy`
2433
- * using `pt-BR` locale: `p` => `HH:mm`
2434
- *
2435
- * Values will be assigned to the date in the descending order of its unit's priority.
2436
- * Units of an equal priority overwrite each other in the order of appearance.
2437
- *
2438
- * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year),
2439
- * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing.
2440
- *
2441
- * `referenceDate` must be passed for correct work of the function.
2442
- * If you're not sure which `referenceDate` to supply, create a new instance of Date:
2443
- * `parse('02/11/2014', 'MM/dd/yyyy', new Date())`
2444
- * In this case parsing will be done in the context of the current date.
2445
- * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`,
2446
- * then `Invalid Date` will be returned.
2447
- *
2448
- * The result may vary by locale.
2449
- *
2450
- * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.
2451
- *
2452
- * If parsing failed, `Invalid Date` will be returned.
2453
- * Invalid Date is a Date, whose time value is NaN.
2454
- * Time value of Date: http://es5.github.io/#x15.9.1.1
2455
- *
2456
- * @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).
2457
- * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
2458
- *
2459
- * @param dateStr - The string to parse
2460
- * @param formatStr - The string of tokens
2461
- * @param referenceDate - defines values missing from the parsed dateString
2462
- * @param options - An object with options.
2463
- * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2464
- * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2465
- *
2466
- * @returns The parsed date
2467
- *
2468
- * @throws `options.locale` must contain `match` property
2469
- * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2470
- * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2471
- * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2472
- * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2473
- * @throws format string contains an unescaped latin alphabet character
2474
- *
2475
- * @example
2476
- * // Parse 11 February 2014 from middle-endian format:
2477
- * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date())
2478
- * //=> Tue Feb 11 2014 00:00:00
2479
- *
2480
- * @example
2481
- * // Parse 28th of February in Esperanto locale in the context of 2010 year:
2482
- * import eo from 'date-fns/locale/eo'
2483
- * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), {
2484
- * locale: eo
2485
- * })
2486
- * //=> Sun Feb 28 2010 00:00:00
2487
- */
2488
- function parse(dateStr, formatStr, referenceDate, options) {
2489
- const invalidDate = () => constructFrom(referenceDate, NaN);
2490
- const defaultOptions = getDefaultOptions();
2491
- const locale = defaultOptions.locale ?? enUS;
2492
-
2493
- const firstWeekContainsDate =
2494
- defaultOptions.firstWeekContainsDate ??
2495
- defaultOptions.locale?.options?.firstWeekContainsDate ??
2496
- 1;
2497
-
2498
- const weekStartsOn =
2499
- defaultOptions.weekStartsOn ??
2500
- defaultOptions.locale?.options?.weekStartsOn ??
2501
- 0;
2502
-
2503
- if (!formatStr)
2504
- return dateStr ? invalidDate() : toDate(referenceDate, options?.in);
2505
-
2506
- const subFnOptions = {
2507
- firstWeekContainsDate,
2508
- weekStartsOn,
2509
- locale,
2510
- };
2511
-
2512
- // If timezone isn't specified, it will try to use the context or
2513
- // the reference date and fallback to the system time zone.
2514
- const setters = [new DateTimezoneSetter(options?.in, referenceDate)];
2515
-
2516
- const tokens = formatStr
2517
- .match(longFormattingTokensRegExp)
2518
- .map((substring) => {
2519
- const firstCharacter = substring[0];
2520
- if (firstCharacter in longFormatters) {
2521
- const longFormatter = longFormatters[firstCharacter];
2522
- return longFormatter(substring, locale.formatLong);
2523
- }
2524
- return substring;
2525
- })
2526
- .join("")
2527
- .match(formattingTokensRegExp);
2528
-
2529
- const usedTokens = [];
2530
-
2531
- for (let token of tokens) {
2532
- if (
2533
- isProtectedWeekYearToken(token)
2534
- ) {
2535
- warnOrThrowProtectedError(token, formatStr, dateStr);
2536
- }
2537
- if (
2538
- isProtectedDayOfYearToken(token)
2539
- ) {
2540
- warnOrThrowProtectedError(token, formatStr, dateStr);
2541
- }
2542
-
2543
- const firstCharacter = token[0];
2544
- const parser = parsers[firstCharacter];
2545
- if (parser) {
2546
- const { incompatibleTokens } = parser;
2547
- if (Array.isArray(incompatibleTokens)) {
2548
- const incompatibleToken = usedTokens.find(
2549
- (usedToken) =>
2550
- incompatibleTokens.includes(usedToken.token) ||
2551
- usedToken.token === firstCharacter,
2552
- );
2553
- if (incompatibleToken) {
2554
- throw new RangeError(
2555
- `The format string mustn't contain \`${incompatibleToken.fullToken}\` and \`${token}\` at the same time`,
2556
- );
2557
- }
2558
- } else if (parser.incompatibleTokens === "*" && usedTokens.length > 0) {
2559
- throw new RangeError(
2560
- `The format string mustn't contain \`${token}\` and any other token at the same time`,
2561
- );
2562
- }
2563
-
2564
- usedTokens.push({ token: firstCharacter, fullToken: token });
2565
-
2566
- const parseResult = parser.run(
2567
- dateStr,
2568
- token,
2569
- locale.match,
2570
- subFnOptions,
2571
- );
2572
-
2573
- if (!parseResult) {
2574
- return invalidDate();
2575
- }
2576
-
2577
- setters.push(parseResult.setter);
2578
-
2579
- dateStr = parseResult.rest;
2580
- } else {
2581
- if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
2582
- throw new RangeError(
2583
- "Format string contains an unescaped latin alphabet character `" +
2584
- firstCharacter +
2585
- "`",
2586
- );
2587
- }
2588
-
2589
- // Replace two single quote characters with one single quote character
2590
- if (token === "''") {
2591
- token = "'";
2592
- } else if (firstCharacter === "'") {
2593
- token = cleanEscapedString(token);
2594
- }
2595
-
2596
- // Cut token from string, or, if string doesn't match the token, return Invalid Date
2597
- if (dateStr.indexOf(token) === 0) {
2598
- dateStr = dateStr.slice(token.length);
2599
- } else {
2600
- return invalidDate();
2601
- }
2602
- }
2603
- }
2604
-
2605
- // Check if the remaining input contains something other than whitespace
2606
- if (dateStr.length > 0 && notWhitespaceRegExp.test(dateStr)) {
2607
- return invalidDate();
2608
- }
2609
-
2610
- const uniquePrioritySetters = setters
2611
- .map((setter) => setter.priority)
2612
- .sort((a, b) => b - a)
2613
- .filter((priority, index, array) => array.indexOf(priority) === index)
2614
- .map((priority) =>
2615
- setters
2616
- .filter((setter) => setter.priority === priority)
2617
- .sort((a, b) => b.subPriority - a.subPriority),
2618
- )
2619
- .map((setterArray) => setterArray[0]);
2620
-
2621
- let date = toDate(referenceDate, options?.in);
2622
-
2623
- if (isNaN(+date)) return invalidDate();
2624
-
2625
- const flags = {};
2626
- for (const setter of uniquePrioritySetters) {
2627
- if (!setter.validate(date, subFnOptions)) {
2628
- return invalidDate();
2629
- }
2630
-
2631
- const result = setter.set(date, flags, subFnOptions);
2632
- // Result is tuple (date, flags)
2633
- if (Array.isArray(result)) {
2634
- date = result[0];
2635
- Object.assign(flags, result[1]);
2636
- // Result is date
2637
- } else {
2638
- date = result;
2639
- }
2640
- }
2641
-
2642
- return date;
2643
- }
2644
-
2645
- function cleanEscapedString(input) {
2646
- return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
2647
- }
2648
-
2649
- const DEFAULT_DATE_FORMAT = "dd/MM/yyyy";
2650
- const DEFAULT_TIME_FORMAT = "HH:mm:ss";
2651
- const SIZE_CONFIG = {
2652
- small: { trigger: "h-7 text-xs", icon: "size-3.5" },
2653
- medium: { trigger: "h-8 text-sm", icon: "size-4" },
2654
- large: { trigger: "h-10 text-sm", icon: "size-4" }
2655
- };
2656
-
2657
- const toNativeDate = (value) => {
2658
- if (value == null) return null;
2659
- if (value instanceof Date) return value;
2660
- if (typeof value.toDate === "function") {
2661
- return value.toDate();
2662
- }
2663
- if (typeof value === "string") {
2664
- const parsed = new Date(value);
2665
- if (!isNaN(parsed.getTime())) return parsed;
2666
- }
2667
- return null;
2668
- };
2669
- const coerceDateValue = (value, type) => {
2670
- if (value == null) return null;
2671
- if (type === "range" && Array.isArray(value)) {
2672
- return [toNativeDate(value[0]), toNativeDate(value[1])];
2673
- }
2674
- return toNativeDate(value);
2675
- };
2676
- const normalizeDateFormat = (fmt) => fmt.replace(/YYYY/g, "yyyy").replace(/YY/g, "yy").replace(/DD/g, "dd").replace(/\bD\b/g, "d");
2677
- const formatDate = (date, formatStr) => {
2678
- if (!date) return "";
2679
- try {
2680
- return format(date, normalizeDateFormat(formatStr));
2681
- } catch {
2682
- return "";
2683
- }
2684
- };
2685
- const parseDate = (str, formatStr) => {
2686
- if (!str) return null;
2687
- try {
2688
- const parsed = parse(str, normalizeDateFormat(formatStr), /* @__PURE__ */ new Date());
2689
- if (!isNaN(parsed.getTime())) return parsed;
2690
- } catch {
2691
- }
2692
- const flexibleFormats = [
2693
- "dd/MM/yyyy",
2694
- "MM/dd/yyyy",
2695
- "yyyy-MM-dd",
2696
- "dd-MM-yyyy",
2697
- "dd/MM/yyyy HH:mm:ss",
2698
- "dd/MM/yyyy HH:mm"
2699
- ];
2700
- for (const fmt of flexibleFormats) {
2701
- if (fmt === formatStr) continue;
2702
- try {
2703
- const parsed = parse(str, fmt, /* @__PURE__ */ new Date());
2704
- if (!isNaN(parsed.getTime())) return parsed;
2705
- } catch {
2706
- continue;
2707
- }
2708
- }
2709
- return null;
2710
- };
2711
- const applyTimeToDate = (date, time) => {
2712
- const result = new Date(date);
2713
- result.setHours(time.hours, time.minutes, time.seconds ?? 0, 0);
2714
- return result;
2715
- };
2716
- const getDisplayFormat = (dateFormat, timeFormat, showTime) => showTime ? `${dateFormat} ${timeFormat}` : dateFormat;
2717
-
2718
- const TIMEZONE_OPTIONS = [
2719
- { label: "Local", value: "" },
2720
- { label: "UTC", value: "utc" }
2721
- ];
2722
- const TimezoneSelect = ({
2723
- value,
2724
- onChange,
2725
- className
2726
- }) => /* @__PURE__ */ jsxs("div", { className: cn("flex items-center gap-1.5 text-sm", className), children: [
2727
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-xs", children: "Timezone" }),
2728
- /* @__PURE__ */ jsx(
2729
- "select",
2730
- {
2731
- value: value ?? "",
2732
- onChange: (e) => onChange(e.target.value || void 0),
2733
- className: cn(
2734
- "rounded-md border border-input bg-background px-2 py-0.5 text-xs",
2735
- "focus:outline-none focus:ring-1 focus:ring-ring"
2736
- ),
2737
- "aria-label": "Select timezone",
2738
- children: TIMEZONE_OPTIONS.map((opt) => /* @__PURE__ */ jsx("option", { value: opt.value, children: opt.label }, opt.value))
2739
- }
2740
- )
2741
- ] });
2742
- TimezoneSelect.displayName = "TimezoneSelect";
2743
-
2744
- const DatePickerFooter = ({
2745
- showTime,
2746
- needConfirm,
2747
- timezone,
2748
- onTimezoneChange,
2749
- onNow,
2750
- onOk,
2751
- className
2752
- }) => {
2753
- const showOkButton = showTime || needConfirm;
2754
- return /* @__PURE__ */ jsxs(
2755
- "div",
2756
- {
2757
- className: cn(
2758
- "flex items-center border-t border-border px-3 py-2",
2759
- className
2760
- ),
2761
- children: [
2762
- /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: onNow, className: "text-xs", children: "Now" }),
2763
- /* @__PURE__ */ jsx("div", { className: "flex-1" }),
2764
- onTimezoneChange && /* @__PURE__ */ jsx(
2765
- TimezoneSelect,
2766
- {
2767
- value: timezone,
2768
- onChange: onTimezoneChange,
2769
- className: "me-2"
2770
- }
2771
- ),
2772
- showOkButton && /* @__PURE__ */ jsx(Button, { size: "sm", onClick: onOk, className: "text-xs", children: "OK" })
2773
- ]
2774
- }
2775
- );
2776
- };
2777
- DatePickerFooter.displayName = "DatePickerFooter";
2778
-
2779
- const DatePicker = forwardRef(
2780
- ({
2781
- value,
2782
- defaultValue,
2783
- onChange,
2784
- type = "date",
2785
- dateFormat = DEFAULT_DATE_FORMAT,
2786
- timeFormat = DEFAULT_TIME_FORMAT,
2787
- showTime = false,
2788
- timePickerFormat = "24",
2789
- showSeconds = false,
2790
- minDate,
2791
- maxDate,
2792
- placeholder,
2793
- label,
2794
- error,
2795
- helpText,
2796
- size = "medium",
2797
- disabled = false,
2798
- allowClear = true,
2799
- required = false,
2800
- timezone,
2801
- onTimezoneChange,
2802
- onOk,
2803
- needConfirm = false,
2804
- onOpenChange,
2805
- className,
2806
- labelProps
2807
- }, ref) => {
2808
- const generatedId = useId();
2809
- const errorId = `error_${generatedId}`;
2810
- const helpTextId = `helpText_${generatedId}`;
2811
- const containerRef = useRef(null);
2812
- const popoverContentId = useRef(
2813
- `datepicker-popover-${generatedId}`
2814
- ).current;
2815
- const [open, setOpen] = useState(false);
2816
- const [internalValue, setInternalValue] = useState(coerceDateValue(defaultValue, type) ?? null);
2817
- const currentValue = value !== void 0 ? coerceDateValue(value, type) : internalValue;
2818
- const [calendarMonth, setCalendarMonth] = useState(
2819
- (type === "date" ? value ?? defaultValue : null) ?? /* @__PURE__ */ new Date()
2820
- );
2821
- const [rangeSelectionStep, setRangeSelectionStep] = useState(
2822
- "from"
2823
- );
2824
- const [pendingDate, setPendingDate] = useState(null);
2825
- const [pendingTime, setPendingTime] = useState({
2826
- hours: 0,
2827
- minutes: 0,
2828
- seconds: 0
2829
- });
2830
- const displayFormat = getDisplayFormat(dateFormat, timeFormat, showTime);
2831
- const sizeConfig = SIZE_CONFIG[size];
2832
- const defaultPlaceholder = showTime ? `${dateFormat.toUpperCase()} ${timeFormat}` : dateFormat.toUpperCase();
2833
- const getDisplayText = useCallback(() => {
2834
- if (type === "range") {
2835
- const rangeValue = currentValue;
2836
- if (!rangeValue || !rangeValue[0] && !rangeValue[1]) return "";
2837
- const from = rangeValue[0] ? formatDate(rangeValue[0], displayFormat) : "";
2838
- const to = rangeValue[1] ? formatDate(rangeValue[1], displayFormat) : "";
2839
- return `${from} - ${to}`;
2840
- }
2841
- return formatDate(currentValue, displayFormat);
2842
- }, [currentValue, displayFormat, type]);
2843
- const [inputText, setInputText] = useState(() => getDisplayText());
2844
- useEffect(() => {
2845
- setInputText(getDisplayText());
2846
- }, [getDisplayText]);
2847
- const closePopover = useCallback(() => {
2848
- setOpen(false);
2849
- onOpenChange?.(false);
2850
- setInputText(getDisplayText());
2851
- }, [onOpenChange, getDisplayText]);
2852
- const openPopover = useCallback(() => {
2853
- setOpen(true);
2854
- onOpenChange?.(true);
2855
- setRangeSelectionStep("from");
2856
- const dateVal = type === "date" ? currentValue : null;
2857
- if (dateVal) {
2858
- setCalendarMonth(dateVal);
2859
- setPendingDate(dateVal);
2860
- setPendingTime(dateToTimeValue(dateVal));
2861
- } else {
2862
- setPendingDate(null);
2863
- setPendingTime({ hours: 0, minutes: 0, seconds: 0 });
2864
- }
2865
- }, [type, currentValue, onOpenChange]);
2866
- useEffect(() => {
2867
- if (!open) return;
2868
- const handlePointerDown = (e) => {
2869
- const target = e.target;
2870
- if (containerRef.current?.contains(target)) return;
2871
- const popoverEl = document.getElementById(popoverContentId);
2872
- if (popoverEl?.contains(target)) return;
2873
- closePopover();
2874
- };
2875
- document.addEventListener("pointerdown", handlePointerDown);
2876
- return () => document.removeEventListener("pointerdown", handlePointerDown);
2877
- }, [open, closePopover]);
2878
- const commitValue = (date) => {
2879
- setInternalValue(date);
2880
- if (date === null) {
2881
- onChange?.(null, "");
2882
- setInputText("");
2883
- } else if (Array.isArray(date)) {
2884
- const formatted = [
2885
- formatDate(date[0], displayFormat),
2886
- formatDate(date[1], displayFormat)
2887
- ];
2888
- onChange?.(date, formatted);
2889
- setInputText(`${formatted[0]} - ${formatted[1]}`);
2890
- } else {
2891
- const formatted = formatDate(date, displayFormat);
2892
- onChange?.(date, formatted);
2893
- setInputText(formatted);
2894
- }
2895
- };
2896
- const handleDateSelect = (selected) => {
2897
- if (!selected) return;
2898
- setCalendarMonth(selected);
2899
- if (showTime || needConfirm) {
2900
- setPendingDate(selected);
2901
- } else {
2902
- commitValue(selected);
2903
- setOpen(false);
2904
- onOpenChange?.(false);
2905
- }
2906
- };
2907
- const handleRangeSelect = (range) => {
2908
- if (!range) return;
2909
- const from = range.from ?? null;
2910
- const to = range.to ?? null;
2911
- if (rangeSelectionStep === "from") {
2912
- setInternalValue([from, null]);
2913
- setRangeSelectionStep("to");
2914
- } else {
2915
- if (from && to) {
2916
- if (showTime || needConfirm) {
2917
- setPendingDate(from);
2918
- } else {
2919
- commitValue([from, to]);
2920
- setOpen(false);
2921
- onOpenChange?.(false);
2922
- }
2923
- } else if (from) {
2924
- setInternalValue([from, null]);
2925
- }
2926
- setRangeSelectionStep("from");
2927
- }
2928
- };
2929
- const handleTimeChange = (time) => {
2930
- setPendingTime(time);
2931
- };
2932
- const handleNow = () => {
2933
- const now = /* @__PURE__ */ new Date();
2934
- if (showTime || needConfirm) {
2935
- setPendingDate(now);
2936
- setPendingTime(dateToTimeValue(now));
2937
- } else {
2938
- commitValue(now);
2939
- setOpen(false);
2940
- onOpenChange?.(false);
2941
- }
2942
- };
2943
- const handleOk = () => {
2944
- if (pendingDate) {
2945
- const finalDate = showTime ? applyTimeToDate(pendingDate, pendingTime) : pendingDate;
2946
- commitValue(finalDate);
2947
- onOk?.(finalDate);
2948
- }
2949
- setOpen(false);
2950
- onOpenChange?.(false);
2951
- };
2952
- const handleClear = (e) => {
2953
- e.stopPropagation();
2954
- e.preventDefault();
2955
- commitValue(null);
2956
- };
2957
- const handleInputChange = (e) => {
2958
- const text = e.target.value;
2959
- setInputText(text);
2960
- if (type === "range") return;
2961
- const parsed = parseDate(text, displayFormat);
2962
- if (parsed) {
2963
- setCalendarMonth(parsed);
2964
- if (showTime || needConfirm) {
2965
- setPendingDate(parsed);
2966
- setPendingTime(dateToTimeValue(parsed));
2967
- } else {
2968
- setInternalValue(parsed);
2969
- }
2970
- }
2971
- };
2972
- const handleInputKeyDown = (e) => {
2973
- if (e.key === "Enter" && type !== "range") {
2974
- const parsed = parseDate(inputText, displayFormat);
2975
- if (parsed) {
2976
- commitValue(parsed);
2977
- }
2978
- setOpen(false);
2979
- onOpenChange?.(false);
2980
- } else if (e.key === "Escape") {
2981
- closePopover();
2982
- }
2983
- };
2984
- const handleInputFocus = () => {
2985
- if (!open) openPopover();
2986
- };
2987
- const hasField = !!(label || error || helpText);
2988
- const showFooter = showTime || needConfirm || !!onTimezoneChange;
2989
- const ariaDescribedBy = [error ? errorId : null, helpText ? helpTextId : null].filter(Boolean).join(" ") || void 0;
2990
- const calendarDisabled = useCallback(
2991
- (date) => {
2992
- if (minDate && date < new Date(minDate.setHours(0, 0, 0, 0)))
2993
- return true;
2994
- if (maxDate && date > new Date(maxDate.setHours(23, 59, 59, 999)))
2995
- return true;
2996
- return false;
2997
- },
2998
- [minDate, maxDate]
2999
- );
3000
- const calendarSelected = useCallback(() => {
3001
- if (showTime || needConfirm) return pendingDate ?? void 0;
3002
- return currentValue ?? void 0;
3003
- }, [showTime, needConfirm, pendingDate, currentValue]);
3004
- const triggerContent = /* @__PURE__ */ jsxs(Popover, { open, children: [
3005
- /* @__PURE__ */ jsx(PopoverAnchor, { asChild: true, children: /* @__PURE__ */ jsxs(
3006
- "div",
3007
- {
3008
- ref: containerRef,
3009
- className: cn(
3010
- "relative flex w-full items-center gap-2 rounded-md border border-input bg-background pe-8 ps-3",
3011
- "focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
3012
- disabled && "cursor-not-allowed opacity-50",
3013
- !!error && "border-destructive ring-destructive/20 ring-3",
3014
- sizeConfig.trigger,
3015
- !hasField && className
3016
- ),
3017
- children: [
3018
- /* @__PURE__ */ jsx(
3019
- Calendar,
3020
- {
3021
- className: cn("shrink-0 text-muted-foreground", sizeConfig.icon)
3022
- }
3023
- ),
3024
- /* @__PURE__ */ jsx(
3025
- "input",
3026
- {
3027
- type: "text",
3028
- disabled,
3029
- "aria-label": label || "Pick a date",
3030
- "aria-describedby": ariaDescribedBy,
3031
- "aria-invalid": !!error || void 0,
3032
- placeholder: placeholder ?? defaultPlaceholder,
3033
- value: inputText,
3034
- onChange: handleInputChange,
3035
- onKeyDown: handleInputKeyDown,
3036
- onFocus: handleInputFocus,
3037
- className: cn(
3038
- "min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground",
3039
- "disabled:cursor-not-allowed",
3040
- sizeConfig.trigger.split(" ").find((c) => c.startsWith("text-"))
3041
- )
3042
- }
3043
- ),
3044
- timezone && /* @__PURE__ */ jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground", children: timezone.toUpperCase() }),
3045
- allowClear && /* @__PURE__ */ jsx(
3046
- "button",
3047
- {
3048
- type: "button",
3049
- onPointerDown: (e) => e.preventDefault(),
3050
- onClick: handleClear,
3051
- className: cn(
3052
- "absolute inset-y-0 end-2 flex items-center text-muted-foreground hover:text-foreground focus:outline-none",
3053
- !(inputText && !disabled) && "invisible"
3054
- ),
3055
- "aria-label": "Clear date",
3056
- tabIndex: -1,
3057
- children: /* @__PURE__ */ jsx(X, { className: sizeConfig.icon })
3058
- }
3059
- )
3060
- ]
3061
- }
3062
- ) }),
3063
- open && /* @__PURE__ */ jsxs(
3064
- PopoverContent,
3065
- {
3066
- id: popoverContentId,
3067
- className: "w-auto p-0",
3068
- align: "start",
3069
- onOpenAutoFocus: (e) => e.preventDefault(),
3070
- onCloseAutoFocus: (e) => e.preventDefault(),
3071
- onPointerDownOutside: (e) => e.preventDefault(),
3072
- onInteractOutside: (e) => e.preventDefault(),
3073
- children: [
3074
- /* @__PURE__ */ jsxs("div", { className: cn("flex", showTime && "flex-row"), children: [
3075
- type === "date" ? /* @__PURE__ */ jsx(
3076
- Calendar$1,
3077
- {
3078
- mode: "single",
3079
- captionLayout: "dropdown",
3080
- month: calendarMonth,
3081
- onMonthChange: setCalendarMonth,
3082
- selected: calendarSelected(),
3083
- onSelect: handleDateSelect,
3084
- disabled: calendarDisabled,
3085
- ...minDate && { fromDate: minDate },
3086
- ...maxDate && { toDate: maxDate }
3087
- }
3088
- ) : /* @__PURE__ */ jsx(
3089
- Calendar$1,
3090
- {
3091
- mode: "range",
3092
- numberOfMonths: 2,
3093
- captionLayout: "dropdown",
3094
- month: calendarMonth,
3095
- onMonthChange: setCalendarMonth,
3096
- selected: currentValue ? {
3097
- from: currentValue[0] ?? void 0,
3098
- to: currentValue[1] ?? void 0
3099
- } : void 0,
3100
- onSelect: handleRangeSelect,
3101
- disabled: calendarDisabled,
3102
- ...minDate && { fromDate: minDate },
3103
- ...maxDate && { toDate: maxDate }
3104
- }
3105
- ),
3106
- showTime && /* @__PURE__ */ jsx("div", { className: "border-inline-start border-border", children: /* @__PURE__ */ jsx(
3107
- TimePickerPanel,
3108
- {
3109
- value: pendingTime,
3110
- onChange: handleTimeChange,
3111
- format: timePickerFormat,
3112
- showSeconds,
3113
- disabled
3114
- }
3115
- ) })
3116
- ] }),
3117
- showFooter && /* @__PURE__ */ jsx(
3118
- DatePickerFooter,
3119
- {
3120
- showTime,
3121
- needConfirm,
3122
- timezone,
3123
- onTimezoneChange,
3124
- onNow: handleNow,
3125
- onOk: handleOk
3126
- }
3127
- )
3128
- ]
3129
- }
3130
- )
3131
- ] });
3132
- if (!hasField) {
3133
- return /* @__PURE__ */ jsx("div", { ref, className, children: triggerContent });
3134
- }
3135
- return /* @__PURE__ */ jsxs(
3136
- Field,
3137
- {
3138
- ref,
3139
- "data-disabled": disabled || void 0,
3140
- "data-invalid": !!error || void 0,
3141
- className,
3142
- children: [
3143
- label && /* @__PURE__ */ jsxs(
3144
- FieldLabel,
3145
- {
3146
- ...labelProps,
3147
- children: [
3148
- label,
3149
- required && /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "text-destructive", children: "*" })
3150
- ]
3151
- }
3152
- ),
3153
- /* @__PURE__ */ jsxs(FieldContent, { children: [
3154
- triggerContent,
3155
- !!error && /* @__PURE__ */ jsx(FieldError, { id: errorId, children: error }),
3156
- helpText && /* @__PURE__ */ jsx(FieldDescription, { id: helpTextId, children: helpText })
3157
- ] })
3158
- ]
3159
- }
3160
- );
3161
- }
3162
- );
3163
- DatePicker.displayName = "DatePicker";
3164
-
3165
- export { DatePicker as D };
3166
- //# sourceMappingURL=DatePicker-CCN3b1oz.js.map