fix(client): crash if locale is incorrect

This commit is contained in:
Elian Doran
2025-10-21 16:54:38 +03:00
parent 10f844f232
commit 797741c7d0
2 changed files with 30 additions and 4 deletions

View File

@@ -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();
});
});

View File

@@ -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.");