From 797741c7d06db92eb37431ccd06d998b4ae36cba Mon Sep 17 00:00:00 2001 From: Elian Doran Date: Tue, 21 Oct 2025 16:54:38 +0300 Subject: [PATCH] fix(client): crash if locale is incorrect --- apps/client/src/utils/formatters.spec.ts | 13 +++++++++++++ apps/client/src/utils/formatters.ts | 21 +++++++++++++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 apps/client/src/utils/formatters.spec.ts diff --git a/apps/client/src/utils/formatters.spec.ts b/apps/client/src/utils/formatters.spec.ts new file mode 100644 index 000000000..4c2f043bc --- /dev/null +++ b/apps/client/src/utils/formatters.spec.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import options from "../services/options"; +import { formatDateTime } from "./formatters"; + +describe("formatDateTime", () => { + it("tolerates incorrect locale", () => { + options.set("formattingLocale", "cn_TW"); + + expect(formatDateTime(new Date())).toBeTruthy(); + expect(formatDateTime(new Date(), "full", "none")).toBeTruthy(); + expect(formatDateTime(new Date(), "none", "full")).toBeTruthy(); + }); +}); diff --git a/apps/client/src/utils/formatters.ts b/apps/client/src/utils/formatters.ts index 40f97e673..ab1263a54 100644 --- a/apps/client/src/utils/formatters.ts +++ b/apps/client/src/utils/formatters.ts @@ -26,14 +26,27 @@ export function formatDateTime(date: string | Date | number | null | undefined, if (timeStyle !== "none" && dateStyle !== "none") { // Format the date and time - const formatter = new Intl.DateTimeFormat(locale, { dateStyle, timeStyle }); - return formatter.format(parsedDate); + try { + const formatter = new Intl.DateTimeFormat(locale, { dateStyle, timeStyle }); + return formatter.format(parsedDate); + } catch (e) { + const formatter = new Intl.DateTimeFormat(undefined, { dateStyle, timeStyle }); + return formatter.format(parsedDate); + } } else if (timeStyle === "none" && dateStyle !== "none") { // Format only the date - return parsedDate.toLocaleDateString(locale, { dateStyle }); + try { + return parsedDate.toLocaleDateString(locale, { dateStyle }); + } catch (e) { + return parsedDate.toLocaleDateString(undefined, { dateStyle }); + } } else if (dateStyle === "none" && timeStyle !== "none") { // Format only the time - return parsedDate.toLocaleTimeString(locale, { timeStyle }); + try { + return parsedDate.toLocaleTimeString(locale, { timeStyle }); + } catch (e) { + return parsedDate.toLocaleTimeString(undefined, { timeStyle }); + } } throw new Error("Incorrect state.");