-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdate-util.ts
More file actions
874 lines (779 loc) · 21.3 KB
/
Copy pathdate-util.ts
File metadata and controls
874 lines (779 loc) · 21.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
import { parseISODate } from '../calendar/helpers.js';
import { clamp, escapeRegex } from '../common/util.js';
export enum FormatDesc {
Numeric = 'numeric',
TwoDigits = '2-digit',
}
export enum DateParts {
Day = 'day',
Month = 'month',
Year = 'year',
Date = 'date',
Hours = 'hours',
Minutes = 'minutes',
Seconds = 'seconds',
AmPm = 'amPm',
Literal = 'literal',
}
export enum DatePart {
Month = 'month',
Year = 'year',
Date = 'date',
Hours = 'hours',
Minutes = 'minutes',
Seconds = 'seconds',
AmPm = 'amPm',
}
/** @ignore */
export interface DatePartInfo {
type: DateParts;
start: number;
end: number;
format: string;
}
export interface DatePartDeltas {
date?: number;
month?: number;
year?: number;
hours?: number;
minutes?: number;
seconds?: number;
}
function isDate(value: unknown): value is Date {
return value instanceof Date;
}
export abstract class DateTimeUtil {
public static readonly DEFAULT_INPUT_FORMAT = 'MM/dd/yyyy';
public static readonly DEFAULT_TIME_INPUT_FORMAT = 'hh:mm tt';
private static readonly SEPARATOR = 'literal';
private static readonly DEFAULT_LOCALE = 'en';
private static readonly PREDEFINED_FORMATS = new Set([
'short',
'medium',
'long',
'full',
]);
public static parseValueFromMask(
inputData: string,
dateTimeParts: DatePartInfo[],
promptChar?: string
): Date | null {
const parts: { [key in DateParts]: number } = {} as any;
dateTimeParts.forEach((dp) => {
let value = Number.parseInt(
DateTimeUtil.getCleanVal(inputData, dp, promptChar),
10
);
if (!value) {
value =
dp.type === DateParts.Date || dp.type === DateParts.Month ? 1 : 0;
}
parts[dp.type] = value;
});
parts[DateParts.Month] -= 1;
if (parts[DateParts.Month] < 0 || 11 < parts[DateParts.Month]) {
return null;
}
// TODO: Century threshold
if (parts[DateParts.Year] < 50) {
parts[DateParts.Year] += 2000;
}
if (
parts[DateParts.Date] >
DateTimeUtil.daysInMonth(parts[DateParts.Year], parts[DateParts.Month])
) {
return null;
}
if (
parts[DateParts.Hours] > 23 ||
parts[DateParts.Minutes] > 59 ||
parts[DateParts.Seconds] > 59
) {
return null;
}
const amPm = dateTimeParts.find((p) => p.type === DateParts.AmPm);
if (amPm) {
parts[DateParts.Hours] %= 12;
}
if (
amPm &&
DateTimeUtil.getCleanVal(inputData, amPm, promptChar).toLowerCase() ===
'pm'
) {
parts[DateParts.Hours] += 12;
}
return new Date(
parts[DateParts.Year] || 2000,
parts[DateParts.Month] || 0,
parts[DateParts.Date] || 1,
parts[DateParts.Hours] || 0,
parts[DateParts.Minutes] || 0,
parts[DateParts.Seconds] || 0
);
}
public static getDefaultMask(locale: string): string {
const parts = DateTimeUtil.getDefaultLocaleMask(
locale || DateTimeUtil.DEFAULT_LOCALE
);
if (parts !== undefined) {
parts.forEach((p: any) => {
if (p.type !== DateParts.Year && p.type !== DateTimeUtil.SEPARATOR) {
p.formatType = FormatDesc.TwoDigits;
}
});
return DateTimeUtil.getMask(parts);
}
return '';
}
public static parseDateTimeFormat(
mask: string,
locale: string = DateTimeUtil.DEFAULT_LOCALE,
noLeadingZero = false
): DatePartInfo[] {
const format = mask || DateTimeUtil.getDefaultMask(locale);
const dateTimeParts: DatePartInfo[] = [];
const formatArray = Array.from(format);
let currentPart: DatePartInfo | null = null;
let position = 0;
for (let i = 0; i < formatArray.length; i++, position++) {
const type = DateTimeUtil.determineDatePart(formatArray[i]);
if (currentPart) {
if (currentPart.type === type) {
currentPart.format += formatArray[i];
if (i < formatArray.length - 1) {
continue;
}
}
DateTimeUtil.addCurrentPart(currentPart, dateTimeParts, noLeadingZero);
position = currentPart.end;
}
currentPart = {
start: position,
end: position + formatArray[i].length,
type,
format: formatArray[i],
};
}
// make sure the last member of a format like H:m:s is not omitted
if (
!dateTimeParts.filter((p) => p.format.includes(currentPart!.format))
.length
) {
DateTimeUtil.addCurrentPart(currentPart!, dateTimeParts, noLeadingZero);
}
// formats like "y" or "yyy" are treated like "yyyy" while editing
const yearPart = dateTimeParts.filter((p) => p.type === DateParts.Year)[0];
if (yearPart && yearPart.format !== 'yy') {
yearPart.end += 4 - yearPart.format.length;
yearPart.format = 'yyyy';
}
return dateTimeParts;
}
public static parseIsoDate(value: string): Date | null {
return parseISODate(value);
}
public static isValidDate(value: any): value is Date {
if (isDate(value)) {
return !Number.isNaN(value.getTime());
}
return false;
}
public static formatDate(
value: Date,
locale: string,
format: string,
noLeadingZero = false
): string {
const options: any = {};
let formattedDate = '';
switch (format) {
case 'short':
case 'long':
case 'medium':
case 'full':
options.dateStyle = format;
options.timeStyle = format;
break;
case 'shortDate':
case 'longDate':
case 'mediumDate':
case 'fullDate':
options.dateStyle = format.toLowerCase().split('date')[0];
break;
case 'shortTime':
case 'longTime':
case 'mediumTime':
case 'fullTime':
options.timeStyle = format.toLowerCase().split('time')[0];
break;
default:
return DateTimeUtil.setDisplayFormatOptions(
value,
format,
locale,
noLeadingZero
);
}
let formatter: Intl.DateTimeFormat;
try {
formatter = new Intl.DateTimeFormat(locale, options);
} catch {
formatter = new Intl.DateTimeFormat(DateTimeUtil.DEFAULT_LOCALE, options);
}
formattedDate = formatter.format(value);
return formattedDate;
}
public static getPartValue(
datePartInfo: DatePartInfo,
partLength: number,
_dateValue: Date | null
): string {
let maskedValue: any;
const datePart = datePartInfo.type;
switch (datePart) {
case DateParts.Date:
maskedValue = _dateValue!.getDate();
break;
case DateParts.Month:
// months are zero based
maskedValue = _dateValue!.getMonth() + 1;
break;
case DateParts.Year:
if (partLength === 2) {
maskedValue = DateTimeUtil.prependValue(
Number.parseInt(_dateValue!.getFullYear().toString().slice(-2), 10),
partLength,
'0'
);
} else {
maskedValue = _dateValue!.getFullYear();
}
break;
case DateParts.Hours:
if (datePartInfo.format.indexOf('h') !== -1) {
maskedValue = DateTimeUtil.prependValue(
DateTimeUtil.toTwelveHourFormat(_dateValue!.getHours()),
partLength,
'0'
);
} else {
maskedValue = _dateValue!.getHours();
}
break;
case DateParts.Minutes:
maskedValue = _dateValue!.getMinutes();
break;
case DateParts.Seconds:
maskedValue = _dateValue!.getSeconds();
break;
case DateParts.AmPm:
maskedValue = _dateValue!.getHours() >= 12 ? 'PM' : 'AM';
break;
}
if (datePartInfo.type !== DateParts.AmPm) {
return DateTimeUtil.prependValue(maskedValue, partLength, '0');
}
return maskedValue;
}
private static _spinTimePart(
newDate: Date,
delta: number,
max: number,
min: number,
setter: (value: number) => number,
getter: () => number,
spinLoop: boolean
): void {
const range = max - min + 1;
let newValue = getter.call(newDate) + delta;
if (spinLoop) {
newValue = min + ((((newValue - min) % range) + range) % range);
} else {
newValue = clamp(newValue, min, max);
}
setter.call(newDate, newValue);
}
public static spinYear(delta: number, newDate: Date): Date {
const maxDate = DateTimeUtil.daysInMonth(
newDate.getFullYear() + delta,
newDate.getMonth()
);
if (newDate.getDate() > maxDate) {
// clip to max to avoid leap year change shifting the entire value
newDate.setDate(maxDate);
}
newDate.setFullYear(newDate.getFullYear() + delta);
return newDate;
}
public static spinMonth(
delta: number,
newDate: Date,
spinLoop: boolean
): void {
const maxDate = DateTimeUtil.daysInMonth(
newDate.getFullYear(),
newDate.getMonth() + delta
);
if (newDate.getDate() > maxDate) {
newDate.setDate(maxDate);
}
const maxMonth = 11;
const minMonth = 0;
let month = newDate.getMonth() + delta;
if (month > maxMonth) {
month = spinLoop ? (month % maxMonth) - 1 : maxMonth;
} else if (month < minMonth) {
month = spinLoop ? maxMonth + (month % maxMonth) + 1 : minMonth;
}
newDate.setMonth(month);
}
public static spinDate(
delta: number,
newDate: Date,
spinLoop: boolean
): void {
const maxDate = DateTimeUtil.daysInMonth(
newDate.getFullYear(),
newDate.getMonth()
);
let date = newDate.getDate() + delta;
if (date > maxDate) {
date = spinLoop ? date % maxDate : maxDate;
} else if (date < 1) {
date = spinLoop ? maxDate + (date % maxDate) : 1;
}
newDate.setDate(date);
}
public static spinHours(
delta: number,
newDate: Date,
spinLoop: boolean
): void {
DateTimeUtil._spinTimePart(
newDate,
delta,
23,
0,
newDate.setHours,
newDate.getHours,
spinLoop
);
}
public static spinMinutes(
delta: number,
newDate: Date,
spinLoop: boolean
): void {
DateTimeUtil._spinTimePart(
newDate,
delta,
59,
0,
newDate.setMinutes,
newDate.getMinutes,
spinLoop
);
}
public static spinSeconds(
delta: number,
newDate: Date,
spinLoop: boolean
): void {
DateTimeUtil._spinTimePart(
newDate,
delta,
59,
0,
newDate.setSeconds,
newDate.getSeconds,
spinLoop
);
}
public static spinAmPm(
newDate: Date,
currentDate: Date,
amPmFromMask: string
): Date {
let date = new Date(newDate);
switch (amPmFromMask) {
case 'AM':
date = new Date(newDate.setHours(newDate.getHours() + 12));
break;
case 'PM':
date = new Date(newDate.setHours(newDate.getHours() - 12));
break;
}
if (date.getDate() !== currentDate.getDate()) {
return currentDate;
}
return date;
}
public static greaterThanMaxValue(
value: Date,
maxValue: Date,
includeTime = true,
includeDate = true
): boolean {
if (includeTime && includeDate) {
return value.getTime() > maxValue.getTime();
}
const _value = new Date(value.getTime());
const _maxValue = new Date(maxValue.getTime());
if (!includeTime) {
_value.setHours(0, 0, 0, 0);
_maxValue.setHours(0, 0, 0, 0);
}
if (!includeDate) {
_value.setFullYear(0, 0, 0);
_maxValue.setFullYear(0, 0, 0);
}
return _value.getTime() > _maxValue.getTime();
}
/**
* Determines whether the provided value is less than the provided min value.
*
* @param includeTime set to false if you want to exclude time portion of the two dates
* @param includeDate set to false if you want to exclude the date portion of the two dates
* @returns true if provided value is less than provided minValue
*/
public static lessThanMinValue(
value: Date,
minValue: Date,
includeTime = true,
includeDate = true
): boolean {
if (includeTime && includeDate) {
return value.getTime() < minValue.getTime();
}
const _value = new Date(value.getTime());
const _minValue = new Date(minValue.getTime());
if (!includeTime) {
_value.setHours(0, 0, 0, 0);
_minValue.setHours(0, 0, 0, 0);
}
if (!includeDate) {
_value.setFullYear(0, 0, 0);
_minValue.setFullYear(0, 0, 0);
}
return _value.getTime() < _minValue.getTime();
}
/**
* Validates a value within a given min and max value range.
*
* @param value The value to validate
* @param minValue The lowest possible value that `value` can take
* @param maxValue The largest possible value that `value` can take
*/
public static validateMinMax(
value: Date,
minValue: Date | string,
maxValue: Date | string,
includeTime = true,
includeDate = true
) {
// if (!value) {
// return null;
// }
const errors = {};
const min = DateTimeUtil.isValidDate(minValue)
? minValue
: DateTimeUtil.parseIsoDate(minValue);
const max = DateTimeUtil.isValidDate(maxValue)
? maxValue
: DateTimeUtil.parseIsoDate(maxValue);
if (
min &&
value &&
DateTimeUtil.lessThanMinValue(value, min, includeTime, includeDate)
) {
Object.assign(errors, { minValue: true });
}
if (
max &&
value &&
DateTimeUtil.greaterThanMaxValue(value, max, includeTime, includeDate)
) {
Object.assign(errors, { maxValue: true });
}
return errors;
}
/**
* Transforms the predefined format to a display format containing only date parts.
*
* @param format The format to check and transform
*/
public static predefinedToDateDisplayFormat(format?: string) {
return format && DateTimeUtil.PREDEFINED_FORMATS.has(format)
? `${format}Date`
: format;
}
private static setDisplayFormatOptions(
value: Date,
format: string,
locale: string,
noLeadingZero = false
) {
const options: any = {};
const parts = DateTimeUtil.parseDateTimeFormat(
format,
locale,
noLeadingZero
);
const datePartFormatOptionMap = new Map([
[DateParts.Date, 'day'],
[DateParts.Month, 'month'],
[DateParts.Year, 'year'],
[DateParts.Hours, 'hour'],
[DateParts.Minutes, 'minute'],
[DateParts.Seconds, 'second'],
[DateParts.AmPm, 'dayPeriod'],
]);
const dateFormatMap = new Map([
['d', 'numeric'],
['dd', '2-digit'],
['M', 'numeric'],
['MM', '2-digit'],
['MMM', 'short'],
['MMMM', 'long'],
['MMMMM', 'narrow'],
['y', 'numeric'],
['yy', '2-digit'],
['yyy', 'numeric'],
['yyyy', 'numeric'],
['h', 'numeric'],
['hh', '2-digit'],
['H', 'numeric'],
['HH', '2-digit'],
['m', 'numeric'],
['mm', '2-digit'],
['s', 'numeric'],
['ss', '2-digit'],
['ttt', 'short'],
['tttt', 'long'],
['ttttt', 'narrow'],
]);
for (const part of parts) {
if (part.type !== DateParts.Literal) {
const option = datePartFormatOptionMap.get(part.type);
const format =
dateFormatMap.get(part.format) ||
dateFormatMap.get(part.format.substring(0, 2));
if (option && format) {
options[option] = format;
if (part.type === DateParts.Hours) {
if (part.format.charAt(0) === 'h') {
options.hourCycle = 'h12';
} else {
options.hourCycle = 'h23';
}
}
}
// Need to be set if we have 't' or 'tt'.
if (part.type === DateParts.AmPm && part.format.length <= 2) {
options.hour = '2-digit';
options.hourCycle = 'h12';
}
}
}
let formatter: Intl.DateTimeFormat;
try {
formatter = new Intl.DateTimeFormat(
locale,
options as Intl.DateTimeFormatOptions
);
} catch {
formatter = new Intl.DateTimeFormat(DateTimeUtil.DEFAULT_LOCALE, options);
}
const formattedParts = formatter.formatToParts(value);
let result = '';
for (const part of parts) {
if (part.type === DateParts.Literal) {
result += part.format;
continue;
}
const option = datePartFormatOptionMap.get(part.type)!;
result += formattedParts.filter((p) => p.type === option)[0]?.value || '';
}
return result;
}
private static getMask(dateStruct: any[]): string {
const mask = [];
for (const part of dateStruct) {
switch (part.formatType) {
case FormatDesc.Numeric: {
if (part.type === DateParts.Day) {
mask.push('d');
} else if (part.type === DateParts.Month) {
mask.push('M');
} else {
mask.push('yyyy');
}
break;
}
case FormatDesc.TwoDigits: {
if (part.type === DateParts.Day) {
mask.push('dd');
} else if (part.type === DateParts.Month) {
mask.push('MM');
} else {
mask.push('yy');
}
}
}
if (part.type === DateTimeUtil.SEPARATOR) {
mask.push(part.value);
}
}
return mask.join('');
}
private static addCurrentPart(
currentPart: DatePartInfo,
dateTimeParts: DatePartInfo[],
noLeadingZero = false
): void {
DateTimeUtil.ensureLeadingZero(currentPart, noLeadingZero);
currentPart.end = currentPart.start + currentPart.format.length;
dateTimeParts.push(currentPart);
}
private static ensureLeadingZero(part: DatePartInfo, noLeadingZero = false) {
switch (part.type) {
case DateParts.Date:
case DateParts.Month:
case DateParts.Hours:
case DateParts.Minutes:
case DateParts.Seconds:
if (part.format.length === 1 && !noLeadingZero) {
part.format = part.format.repeat(2);
}
break;
}
}
private static determineDatePart(char: string): DateParts {
switch (char) {
case 'd':
case 'D':
return DateParts.Date;
case 'M':
return DateParts.Month;
case 'y':
case 'Y':
return DateParts.Year;
case 'h':
case 'H':
return DateParts.Hours;
case 'm':
return DateParts.Minutes;
case 's':
case 'S':
return DateParts.Seconds;
case 't':
case 'T':
return DateParts.AmPm;
default:
return DateParts.Literal;
}
}
private static getDefaultLocaleMask(locale: string) {
const dateStruct: any = [];
let formatter: Intl.DateTimeFormat;
try {
formatter = new Intl.DateTimeFormat(locale);
} catch {
return;
}
const formatToParts = formatter.formatToParts(new Date());
for (const part of formatToParts) {
if (part.type === DateTimeUtil.SEPARATOR) {
dateStruct.push({
type: DateTimeUtil.SEPARATOR,
value: part.value,
});
} else {
dateStruct.push({
type: part.type,
});
}
}
const formatterOptions = formatter.resolvedOptions();
for (const part of dateStruct) {
switch (part.type) {
case DateParts.Day: {
part.formatType = formatterOptions.day;
break;
}
case DateParts.Month: {
part.formatType = formatterOptions.month;
break;
}
case DateParts.Year: {
part.formatType = formatterOptions.year;
break;
}
}
}
DateTimeUtil.fillDatePartsPositions(dateStruct);
return dateStruct;
}
private static fillDatePartsPositions(dateArray: any[]): void {
let currentPos = 0;
for (const part of dateArray) {
// Day|Month part positions
if (part.type === DateParts.Day || part.type === DateParts.Month) {
// Offset 2 positions for number
part.position = [currentPos, currentPos + 2];
currentPos += 2;
} else if (part.type === DateParts.Year) {
// Year part positions
switch (part.formatType) {
case FormatDesc.Numeric: {
// Offset 4 positions for full year
part.position = [currentPos, currentPos + 4];
currentPos += 4;
break;
}
case FormatDesc.TwoDigits: {
// Offset 2 positions for short year
part.position = [currentPos, currentPos + 2];
currentPos += 2;
break;
}
}
} else if (part.type === DateTimeUtil.SEPARATOR) {
// Separator positions
part.position = [currentPos, currentPos + 1];
currentPos++;
}
}
}
private static getCleanVal(
inputData: string,
datePart: DatePartInfo,
prompt?: string
): string {
return DateTimeUtil.trimEmptyPlaceholders(
inputData.substring(datePart.start, datePart.end),
prompt
);
}
private static trimEmptyPlaceholders(value: string, prompt?: string): string {
const result = value.replace(
new RegExp(escapeRegex(prompt ?? '_'), 'g'),
''
);
return result;
}
private static daysInMonth(fullYear: number, month: number): number {
return new Date(fullYear, month + 1, 0).getDate();
}
private static prependValue(
value: number,
partLength: number,
prependChar: string
): string {
return (prependChar + value.toString()).slice(-partLength);
}
private static toTwelveHourFormat(value: number): number {
const hour12 = value % 12;
return hour12 === 0 ? 12 : hour12;
}
}