-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.js
More file actions
826 lines (749 loc) · 26 KB
/
Copy pathfunctions.js
File metadata and controls
826 lines (749 loc) · 26 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
const {
iso6391_languages,
default_en_day_number,
day_numbers,
cache_ttl,
month_numbers,
timeInMilliseconds,
format_types,
cached_dateTimeFormat,
timezone_cache,
timezone_check_cache,
timezone_abbreviation_cache,
long_timezone_cache,
timezone_formatter_cache,
global_config,
systemTimezone,
cached_converter_int,
converter_results_cache,
cached_dateTimeFormat_with_locale,
COMMON_TIMEZONES,
ordinal_suffix,
} = require('./constants');
const months = {};
const days = {};
/**
* Returns ordinal suffix for a number (1st, 2nd, 3rd, 4th, etc.)
* @param {number} n - The number to get ordinal suffix for
* @returns {string} The number with ordinal suffix
*/
function getOrdinal(n) {
const v = n % 100;
return n + (ordinal_suffix[(v - 20) % 10] || ordinal_suffix[v] || ordinal_suffix[0]);
}
for (const key in iso6391_languages) {
const month_long = new Intl.DateTimeFormat(key, { month: 'long' });
const month_short = new Intl.DateTimeFormat(key, { month: 'short' });
const day_long = new Intl.DateTimeFormat(key, { weekday: 'long' });
const day_short = new Intl.DateTimeFormat(key, { weekday: 'short' });
for (let i = 1; i < 13; i++) {
const date = new Date(2021, i, '0');
months[month_long.format(date).toLowerCase()] = i;
months[month_short.format(date).toLowerCase()] = i;
}
for (let i = 1; i < 8; i++) {
const date = new Date(2021, 1, i);
const number = parseInt(default_en_day_number.format(date), 10);
days[day_long.format(date).toLowerCase()] = number;
days[day_short.format(date).toLowerCase()] = number;
}
}
/**
* if valid will be turn english month name
*
* @param {string} monthName
* @returns {string|Boolean}
*/
function isValidMonth(monthName) {
const monthNameLower = monthName.toLowerCase();
return months[monthNameLower] ? month_numbers[months[monthNameLower]] : false;
}
/**
* if valid will be turn english day name
*
* @param {string} dayname
* @returns {string|Boolean}
*/
function isValidDayName(dayname) {
const dayNameLower = dayname.toLowerCase();
return days[dayNameLower] ? day_numbers[days[dayNameLower]] : false;
}
/**
* Enhanced timezone offset calculation with DST support
*
* @param {string} timezone - IANA timezone identifier
* @param {Date} date - Date for which to calculate offset (defaults to current date)
* @returns {number} - Offset in milliseconds
*/
function getTimezoneOffset(timezone, date = new Date()) {
// Validate timezone first (outside try-catch for proper error handling)
checkTimezone(timezone);
// Check cache first
const cacheKey = `${timezone}_${date.getTime()}`;
if (timezone_cache.has(cacheKey)) {
const { offset, timestamp } = timezone_cache.get(cacheKey);
if (date.getTime() - timestamp < cache_ttl) {
return offset;
}
}
try {
let formatter;
if (long_timezone_cache.has(timezone)) {
formatter = long_timezone_cache.get(timezone);
} else {
formatter = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
timeZoneName: 'longOffset',
});
long_timezone_cache.set(timezone, formatter);
}
// Get timezone offset using Intl.DateTimeFormat with timeZoneName
const parts = formatter.formatToParts(date);
const offsetPart = parts.find((part) => part.type === 'timeZoneName');
if (!offsetPart) {
throw new Error('Could not determine timezone offset');
}
let offsetStr = offsetPart.value.replace('GMT', '');
// Handle Hermes/React Native where GMT offset is split into multiple parts
// e.g., [timeZoneName: "GMT"], [literal: "+"], [literal: "03"], [literal: ":"], [timeZoneName: "00"]
if (offsetStr === '' || offsetStr === 'GMT') {
// Try to reconstruct offset from split parts
const gmtIndex = parts.findIndex((p) => p.type === 'timeZoneName' && (p.value === 'GMT' || p.value.startsWith('GMT')));
if (gmtIndex !== -1) {
// Collect subsequent parts that form the offset
let reconstructed = '';
for (let i = gmtIndex + 1; i < parts.length; i++) {
const part = parts[i];
// Stop if we hit a non-offset part (another timeZoneName that's not numeric)
if (part.type === 'timeZoneName' && !/^\d+$/.test(part.value)) {
break;
}
// Collect literals (+, -, :, digits) and numeric timeZoneName parts
if (part.type === 'literal' || (part.type === 'timeZoneName' && /^\d+$/.test(part.value))) {
reconstructed += part.value;
}
}
if (reconstructed) {
offsetStr = reconstructed;
}
}
}
// If still empty or invalid, fallback
if (!offsetStr || offsetStr === '' || offsetStr === 'GMT') {
throw new Error('Invalid offset parsing - falling back');
}
const isNegative = offsetStr.startsWith('-');
const timeStr = offsetStr.replace(/[+-]/, '');
const [hours, minutes = '0'] = timeStr.split(':').map(Number);
const totalMinutes = hours * 60 + minutes;
// Check for NaN (Hermes splits timeZoneName into multiple parts)
if (Number.isNaN(totalMinutes)) {
throw new Error('Invalid offset parsing - falling back');
}
// For timezone conversion, we need the offset from UTC to the target timezone
// GMT-05:00 means the timezone is 5 hours behind UTC, so offset should be -5
// GMT+08:00 means the timezone is 8 hours ahead of UTC, so offset should be +8
const offsetMs = (isNegative ? -totalMinutes : totalMinutes) * 60 * 1000;
// Cache the result
timezone_cache.set(cacheKey, {
offset: offsetMs,
timestamp: date.getTime(),
});
return offsetMs;
} catch {
// Fallback: Use date comparison method (Hermes/React Native compatible)
return getTimezoneOffsetFallback(timezone, date, cacheKey);
}
}
/**
* Fallback method for timezone offset calculation
* Used when longOffset is not supported (e.g., React Native Hermes)
*
* @param {string} timezone - IANA timezone identifier
* @param {Date} date - Date for which to calculate offset
* @param {string} cacheKey - Cache key for storing result
* @returns {number} - Offset in milliseconds
*/
function getTimezoneOffsetFallback(timezone, date, cacheKey) {
try {
const formatter = new Intl.DateTimeFormat('en-CA', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
});
const parts = formatter.formatToParts(date);
const p = {};
for (const part of parts) {
p[part.type] = part.value;
}
// Handle hour: '24' edge case (midnight)
let hour = parseInt(p.hour, 10);
let dayOffset = 0;
if (hour === 24) {
hour = 0;
dayOffset = 86400000; // 1 day in ms
}
const tzTimeAsUtc =
Date.UTC(parseInt(p.year, 10), parseInt(p.month, 10) - 1, parseInt(p.day, 10), hour, parseInt(p.minute, 10), parseInt(p.second, 10)) +
dayOffset;
// Add milliseconds from original date (formatter doesn't include ms)
const offsetMs = tzTimeAsUtc - (date.getTime() - date.getMilliseconds());
// Cache the result
if (cacheKey) {
timezone_cache.set(cacheKey, {
offset: offsetMs,
timestamp: date.getTime(),
});
}
return offsetMs;
} catch {
throw new Error(`Invalid timezone: ${timezone}`);
}
}
/**
* Check if timezone is valid
*
* @param {string} timezone - IANA timezone identifier
* @returns {boolean}
*/
function checkTimezone(timezone) {
try {
if (timezone_check_cache.has(timezone)) {
return true;
}
// Test if timezone is valid by trying to format a date
new Intl.DateTimeFormat('en-US', { timeZone: timezone }).format(new Date());
timezone_check_cache.set(timezone, true);
return true;
} catch {
throw new Error(`Invalid timezone: ${timezone}`);
}
}
/**
* Get timezone information including DST status
*
* @param {string} timezone - IANA timezone identifier
* @param {Date} date - Date for which to get info (defaults to current date)
* @returns {object} - Timezone information
*/
function getTimezoneInfo(timezone, date = new Date()) {
try {
checkTimezone(timezone);
// Get current offset
const currentOffset = getTimezoneOffset(timezone, date);
// Get offset for same date in winter (to detect DST)
const winterDate = new Date(date.getFullYear(), 0, 1); // January 1st
const winterOffset = getTimezoneOffset(timezone, winterDate);
// Get offset for same date in summer (to detect DST)
const summerDate = new Date(date.getFullYear(), 6, 1); // July 1st
const summerOffset = getTimezoneOffset(timezone, summerDate);
// Determine if DST is active
const isDST = currentOffset !== winterOffset;
let formatter;
if (timezone_abbreviation_cache.has(timezone)) {
formatter = timezone_abbreviation_cache.get(timezone);
} else {
formatter = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
timeZoneName: 'short',
});
timezone_abbreviation_cache.set(timezone, formatter);
}
// Get timezone abbreviation
const abbreviation = formatter.formatToParts(date).find((part) => part.type === 'timeZoneName')?.value || timezone;
return {
timezone,
offset: currentOffset,
isDST,
abbreviation,
standardOffset: winterOffset,
daylightOffset: summerOffset,
};
} catch (error) {
throw new Error(`Failed to get timezone info for ${timezone}: ${error.message}`);
}
}
/**
* Enhanced timezone parsing with automatic DST detection
*
* @param {KkDate} kkDate - KkDate instance
* @param {boolean} is_init - Whether this is initial parsing
* @returns {Date} - Parsed date with timezone conversion
*/
function parseWithTimezone(kkDate) {
// If this is a .tz() call, convert to target timezone
if (kkDate.temp_config.timezone) {
const targetTimezone = kkDate.temp_config.timezone;
// Special handling for UTC - return original UTC time
if (targetTimezone === 'UTC') {
return kkDate.date;
}
// For .tz() calls, we don't change the date object
// The timezone information is stored in temp_config.timezone
// and the format function will handle the display conversion
return kkDate.date;
}
// Constructor call - reinterpret input in global timezone if:
// 1. Global timezone is set and different from system timezone
// 2. Input is not ISO8601 UTC timestamp
// 3. Global timezone will be used for formatting (not just UTC display)
// 4. Input is not 'now' (current time should not be reinterpreted)
const globalTimezone = global_config.timezone;
if (
globalTimezone &&
globalTimezone !== systemTimezone &&
kkDate.detected_format !== 'ISO8601' &&
kkDate.detected_format !== 'now' &&
kkDate.detected_format !== 'Xx' &&
kkDate.detected_format !== 'kkDate'
) {
// Reinterpret the input as being in global timezone
const systemOffset = getTimezoneOffset(systemTimezone, kkDate.date);
const globalOffset = getTimezoneOffset(globalTimezone, kkDate.date);
const offsetDiff = globalOffset - systemOffset;
// Adjust the date to represent the same clock time in global timezone
const adjustedTime = kkDate.date.getTime() - offsetDiff;
return new Date(adjustedTime);
}
return kkDate.date;
}
/**
* Convert date to specific timezone
*
* @param {Date} date - Date to convert
* @param {string} targetTimezone - Target timezone
* @param {string} sourceTimezone - Source timezone (optional, defaults to user timezone)
* @returns {Date} - Converted date
*/
function convertToTimezone(date, targetTimezone, sourceTimezone = global_config.userTimezone) {
try {
checkTimezone(targetTimezone);
checkTimezone(sourceTimezone);
const targetOffset = getTimezoneOffset(targetTimezone, date);
const sourceOffset = getTimezoneOffset(sourceTimezone, date);
const timezoneDiff = targetOffset - sourceOffset;
return new Date(date.getTime() + timezoneDiff);
} catch (error) {
throw new Error(`Failed to convert timezone: ${error.message}`);
}
}
/**
* Get all available timezones (if supported by the environment)
*
* @returns {string[]} - Array of available timezone identifiers
*/
function getAvailableTimezones() {
try {
return COMMON_TIMEZONES.filter((tz) => {
try {
checkTimezone(tz);
return true;
} catch {
return false;
}
});
} catch {
return ['UTC']; // Fallback to UTC only
}
}
/**
* Check if a date is in DST for a given timezone
*
* @param {string} timezone - IANA timezone identifier
* @param {Date} date - Date to check (defaults to current date)
* @returns {boolean} - True if DST is active
*/
function isDST(timezone, date = new Date()) {
try {
const info = getTimezoneInfo(timezone, date);
return info.isDST;
} catch {
return false;
}
}
/**
* Get timezone abbreviation
*
* @param {string} timezone - IANA timezone identifier
* @param {Date} date - Date for abbreviation (defaults to current date)
* @returns {string} - Timezone abbreviation
*/
function getTimezoneAbbreviation(timezone, date = new Date()) {
try {
const info = getTimezoneInfo(timezone, date);
return info.abbreviation;
} catch {
return timezone;
}
}
/**
* absFloor function
*
* @param {number} number
* @returns {number}
*/
function absFloor(number) {
if (number < 0) {
return Math.ceil(number) || 0;
}
return Math.floor(number);
}
/**
* padZero
*
* @param {number} num
* @returns {string}
*/
const padZero = (num) => String(num).padStart(2, '0');
/**
* @description It divides the date string into parts and returns an object.
* @param {string} time
* @param {"years" | "months" | "weeks" | "days" | "hours" | "minutes" | "seconds"} type
* @returns {{years: number, months: number, weeks: number, days: number, hours: number, minutes: number, seconds: number, milliseconds: number, $kk_date: {milliseconds: number}, asMilliseconds: function(): number, asSeconds: function(): number, asMinutes: function(): number, asHours: function(): number, asDays: function(): number, asWeeks: function(): number, asMonths: function(): number, asYears: function(): number}}
* @example
* // Example usage:
* const result = duration(1234, 'minute');
* console.log(result);
* // Output: { years: 0, months: 0, weeks: 0, days: 0, hours: 20, minutes: 34, seconds: 0, milliseconds: 0 }
*/
function duration(time, type) {
if (!Number.isInteger(time)) {
throw new Error('Invalid time');
}
const _milliseconds = time * timeInMilliseconds[type];
const response = {
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0,
$kk_date: { milliseconds: 0 },
asMilliseconds: () => _milliseconds,
asSeconds: () => _milliseconds / timeInMilliseconds.seconds,
asMinutes: () => _milliseconds / timeInMilliseconds.minutes,
asHours: () => _milliseconds / timeInMilliseconds.hours,
asDays: () => _milliseconds / timeInMilliseconds.days,
asWeeks: () => _milliseconds / timeInMilliseconds.weeks,
asMonths: () => _milliseconds / timeInMilliseconds.months,
asYears: () => _milliseconds / timeInMilliseconds.years,
};
if (!time || typeof time !== 'number' || time < 0) {
throw new Error('Invalid time');
}
if (!timeInMilliseconds[type]) {
throw new Error('Invalid type');
}
response.$kk_date.milliseconds = _milliseconds;
let milliseconds = _milliseconds;
response.years = Math.floor(milliseconds / timeInMilliseconds.years);
milliseconds = milliseconds % timeInMilliseconds.years;
response.months = Math.floor(milliseconds / timeInMilliseconds.months);
milliseconds = milliseconds % timeInMilliseconds.months;
response.weeks = Math.floor(milliseconds / timeInMilliseconds.weeks);
milliseconds = milliseconds % timeInMilliseconds.weeks;
response.days = Math.floor(milliseconds / timeInMilliseconds.days);
milliseconds = milliseconds % timeInMilliseconds.days;
response.hours = Math.floor(milliseconds / timeInMilliseconds.hours);
milliseconds = milliseconds % timeInMilliseconds.hours;
response.minutes = Math.floor(milliseconds / timeInMilliseconds.minutes);
milliseconds = milliseconds % timeInMilliseconds.minutes;
response.seconds = Math.floor(milliseconds / timeInMilliseconds.seconds);
milliseconds = milliseconds % timeInMilliseconds.seconds;
response.milliseconds = milliseconds;
return response;
}
/**
* @description It formats the date with the locale and template.
* @param {KkDate} orj_this
* @param {string} template
* @returns {Intl.DateTimeFormat}
*/
function dateTimeFormat(orj_this, template) {
const tempLocale = orj_this.temp_config.locale;
// For timestamp inputs with configured timezone, use timezone-aware formatting
// For timestamp inputs with configured timezone, use timezone-aware formatting
const timezone = orj_this.temp_config.timezone || global_config.timezone;
if (timezone) {
const locale = tempLocale || global_config.locale;
if (template === format_types.dddd) {
if (cached_dateTimeFormat_with_locale.dddd[`${locale}_${timezone}`]) {
return cached_dateTimeFormat_with_locale.dddd[`${locale}_${timezone}`];
}
cached_dateTimeFormat_with_locale.dddd[`${locale}_${timezone}`] = {
value: new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: timezone }),
id: `${locale}_${timezone}_dddd`,
};
return cached_dateTimeFormat_with_locale.dddd[`${locale}_${timezone}`];
}
if (template === format_types.ddd) {
if (cached_dateTimeFormat_with_locale.ddd[`${locale}_${timezone}`]) {
return cached_dateTimeFormat_with_locale.ddd[`${locale}_${timezone}`];
}
cached_dateTimeFormat_with_locale.ddd[`${locale}_${timezone}`] = {
value: new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: timezone }),
id: `${locale}_${timezone}_ddd`,
};
return cached_dateTimeFormat_with_locale.ddd[`${locale}_${timezone}`];
}
if (template === format_types.MMMM) {
if (cached_dateTimeFormat_with_locale.MMMM[`${locale}_${timezone}`]) {
return cached_dateTimeFormat_with_locale.MMMM[`${locale}_${timezone}`];
}
cached_dateTimeFormat_with_locale.MMMM[`${locale}_${timezone}`] = {
value: new Intl.DateTimeFormat(locale, { month: 'long', timeZone: timezone }),
id: `${locale}_${timezone}_MMMM`,
};
return cached_dateTimeFormat_with_locale.MMMM[`${locale}_${timezone}`];
}
if (template === format_types.MMM) {
if (cached_dateTimeFormat_with_locale.MMM[`${locale}_${timezone}`]) {
return cached_dateTimeFormat_with_locale.MMM[`${locale}_${timezone}`];
}
cached_dateTimeFormat_with_locale.MMM[`${locale}_${timezone}`] = {
value: new Intl.DateTimeFormat(locale, { month: 'short', timeZone: timezone }),
id: `${locale}_${timezone}_MMM`,
};
return cached_dateTimeFormat_with_locale.MMM[`${locale}_${timezone}`];
}
}
if (tempLocale) {
return { value: cached_dateTimeFormat.temp[template][tempLocale], id: `${orj_this.temp_config.locale}_0` };
}
if (template === format_types.dddd) {
return { value: cached_dateTimeFormat.dddd, id: '1' };
}
if (template === format_types.ddd) {
return { value: cached_dateTimeFormat.ddd, id: '2' };
}
if (template === format_types.MMMM) {
return { value: cached_dateTimeFormat.MMMM, id: '3' };
}
if (template === format_types.MMM) {
return { value: cached_dateTimeFormat.MMM, id: '4' };
}
throw new Error('unkown template for dateTimeFormat !');
}
/**
* date converter - OPTIMIZED VERSION
*
* @param {Date} date
* @param {Array} to
* @param {object} [options={pad: true, isUTC: false, detectedFormat: null}]
* @returns {Object}
*/
function converter(date, to, options = { pad: true }) {
const shouldPad = options.pad !== false;
const isUTC = options.isUTC || false;
const detectedFormat = options.detectedFormat || null;
const orj_this = options.orj_this;
// Determine timezone for formatting
let targetTimezone = null;
if (orj_this) {
targetTimezone = orj_this.temp_config.timezone || global_config.timezone;
}
// Create cache key for this specific conversion
const timestamp = date.getTime();
const cacheKey = `${timestamp}_${to.join(',')}_${shouldPad}_${isUTC}_${targetTimezone || 'none'}_${detectedFormat || 'none'}`;
// Check cache first
if (converter_results_cache.has(cacheKey)) {
return converter_results_cache.get(cacheKey);
}
// Limit cache size to prevent memory leaks
if (converter_results_cache.size > 10000) {
// Clear half of the cache when limit is reached
const keysToDelete = Array.from(converter_results_cache.keys()).slice(0, 5000);
for (const key of keysToDelete) {
converter_results_cache.delete(key);
}
}
const result = {};
// Use timezone-aware formatting if targetTimezone is specified and not UTC
// For ISO8601 UTC timestamps with .tz() calls, we also need timezone formatting
if (targetTimezone && targetTimezone !== 'UTC') {
// Use Intl.DateTimeFormat for timezone-aware formatting
let formatter = null;
const partsMap = {};
if (cached_converter_int[targetTimezone]) {
formatter = cached_converter_int[targetTimezone];
} else {
formatter = new Intl.DateTimeFormat('en-CA', {
timeZone: targetTimezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
});
cached_converter_int[targetTimezone] = formatter;
}
const parts = formatter.formatToParts(date);
for (const part of parts) {
partsMap[part.type] = part.value;
}
const len = to.length;
for (let i = 0; i < len; i++) {
const field = to[i];
switch (field) {
case 'year':
result.year = partsMap.year;
break;
case 'month':
result.month = shouldPad ? partsMap.month : parseInt(partsMap.month, 10);
break;
case 'day':
result.day = shouldPad ? partsMap.day : parseInt(partsMap.day, 10);
break;
case 'hours':
// Fix: Convert hour 24 to 00 (midnight)
result.hours = partsMap.hour === '24' ? '00' : shouldPad ? partsMap.hour : parseInt(partsMap.hour, 10);
break;
case 'minutes':
result.minutes = shouldPad ? partsMap.minute : parseInt(partsMap.minute, 10);
break;
case 'seconds':
result.seconds = shouldPad ? partsMap.second : parseInt(partsMap.second, 10);
break;
case 'milliseconds':
result.milliseconds = shouldPad
? date.getMilliseconds() < 100
? `0${date.getMilliseconds() < 10 ? `0${date.getMilliseconds()}` : date.getMilliseconds()}`
: String(date.getMilliseconds())
: date.getMilliseconds();
break;
}
}
converter_results_cache.set(cacheKey, result);
return result;
}
// Fast path: Use direct Date methods for most cases
if (detectedFormat !== 'Xx' || !global_config.timezone || global_config.timezone === 'UTC') {
// Standard formatting - much faster
const len = to.length;
for (let i = 0; i < len; i++) {
const field = to[i];
switch (field) {
case 'year':
result.year = isUTC ? date.getUTCFullYear() : date.getFullYear();
break;
case 'month': {
const month = (isUTC ? date.getUTCMonth() : date.getMonth()) + 1;
result.month = shouldPad ? (month < 10 ? `0${month}` : String(month)) : month;
break;
}
case 'day': {
const day = isUTC ? date.getUTCDate() : date.getDate();
result.day = shouldPad ? (day < 10 ? `0${day}` : String(day)) : day;
break;
}
case 'hours': {
const hours = isUTC ? date.getUTCHours() : date.getHours();
result.hours = shouldPad ? (hours < 10 ? `0${hours}` : String(hours)) : hours;
break;
}
case 'minutes': {
const minutes = isUTC ? date.getUTCMinutes() : date.getMinutes();
result.minutes = shouldPad ? (minutes < 10 ? `0${minutes}` : String(minutes)) : minutes;
break;
}
case 'seconds': {
const seconds = isUTC ? date.getUTCSeconds() : date.getSeconds();
result.seconds = shouldPad ? (seconds < 10 ? `0${seconds}` : String(seconds)) : seconds;
break;
}
case 'milliseconds': {
const ms = isUTC ? date.getUTCMilliseconds() : date.getMilliseconds();
result.milliseconds = shouldPad ? (ms < 100 ? (ms < 10 ? `00${ms}` : `0${ms}`) : String(ms)) : ms;
break;
}
}
}
converter_results_cache.set(cacheKey, result);
return result;
}
// Timezone-aware formatting only when absolutely necessary
const useTimezone = targetTimezone || global_config.timezone;
// Cache the DateTimeFormat instance for performance
let formatter_value;
if (timezone_formatter_cache.has(useTimezone)) {
formatter_value = timezone_formatter_cache.get(useTimezone);
} else {
formatter_value = new Intl.DateTimeFormat('en-CA', {
timeZone: useTimezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
});
timezone_formatter_cache.set(useTimezone, formatter_value);
}
// Format the specific date
const parts = formatter_value.formatToParts(date);
const in_result = {};
const partsLen = parts.length;
// Optimized parts mapping
for (let i = 0; i < partsLen; i++) {
const part = parts[i];
in_result[part.type] = part.value;
}
// Process requested fields
const len = to.length;
for (let i = 0; i < len; i++) {
const field = to[i];
switch (field) {
case 'year':
result.year = in_result.year;
break;
case 'month':
result.month = shouldPad ? in_result.month : parseInt(in_result.month, 10);
break;
case 'day':
result.day = shouldPad ? in_result.day : parseInt(in_result.day, 10);
break;
case 'hours':
result.hours = shouldPad ? in_result.hour : parseInt(in_result.hour, 10);
break;
case 'minutes':
result.minutes = shouldPad ? in_result.minute : parseInt(in_result.minute, 10);
break;
case 'seconds':
result.seconds = shouldPad ? in_result.second : parseInt(in_result.second, 10);
break;
case 'milliseconds': {
const ms = date.getMilliseconds();
result.milliseconds = shouldPad ? (ms < 100 ? (ms < 10 ? `00${ms}` : `0${ms}`) : String(ms)) : ms;
break;
}
}
}
converter_results_cache.set(cacheKey, result);
return result;
}
module.exports.getTimezoneOffset = getTimezoneOffset;
module.exports.parseWithTimezone = parseWithTimezone;
module.exports.checkTimezone = checkTimezone;
module.exports.getTimezoneInfo = getTimezoneInfo;
module.exports.convertToTimezone = convertToTimezone;
module.exports.getAvailableTimezones = getAvailableTimezones;
module.exports.isDST = isDST;
module.exports.getTimezoneAbbreviation = getTimezoneAbbreviation;
module.exports.padZero = padZero;
module.exports.absFloor = absFloor;
module.exports.duration = duration;
module.exports.dateTimeFormat = dateTimeFormat;
module.exports.converter = converter;
module.exports.isValidMonth = isValidMonth;
module.exports.isValidDayName = isValidDayName;
module.exports.getOrdinal = getOrdinal;