From fe98ecff04cd825eca028673f6197a093ba1703d Mon Sep 17 00:00:00 2001
From: co-sic
Date: Wed, 23 Oct 2024 10:58:40 +0200
Subject: [PATCH] fix: add caching for intl formatter
---
src/CalendarDate.ts | 26 +++++++++++++++++++++-----
1 file changed, 21 insertions(+), 5 deletions(-)
diff --git a/src/CalendarDate.ts b/src/CalendarDate.ts
index fa3a016..080cd69 100644
--- a/src/CalendarDate.ts
+++ b/src/CalendarDate.ts
@@ -34,6 +34,12 @@ export class CalendarDate {
*/
readonly weekday!: number;
+ /**
+ * cache for Intl.DateTimeFormat instances
+ * @private
+ */
+ private static dateTimeFormatterByTimezone = new Map();
+
/**
* Customizes the default string description for instances of `CalendarDate`.
*/
@@ -108,6 +114,20 @@ export class CalendarDate {
return month === 2 && CalendarDate.isLeapYear(year) ? 29 : DAYS_IN_MONTH[month - 1];
}
+ private static getIntlDateTimeFormatter(timeZone: string): Intl.DateTimeFormat {
+ let formatter = CalendarDate.dateTimeFormatterByTimezone.get(timeZone);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat('en-CA', {
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ timeZone,
+ });
+ CalendarDate.dateTimeFormatterByTimezone.set(timeZone, formatter);
+ }
+ return formatter;
+ }
+
/**
* returns a CalendarDate instance for the supplied Date, using UTC values
*/
@@ -126,11 +146,7 @@ export class CalendarDate {
* returns a CalendarDate instance for the supplied Date, using the supplied time zone string
*/
static fromDateWithTimeZone(date: Date, timeZone: string): CalendarDate {
- const calendarValues = date
- .toLocaleDateString('de-DE', { timeZone })
- .split('.')
- .map((value) => parseInt(value));
- return new CalendarDate(calendarValues[2], calendarValues[1], calendarValues[0]);
+ return new CalendarDate(CalendarDate.getIntlDateTimeFormatter(timeZone).format(date));
}
/**