Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(client): crash if locale is incorrect
Elian Doran797741c7d06d
diff --git a/apps/client/src/utils/formatters.spec.ts b/apps/client/src/utils/formatters.spec.tsnew file mode 100644index 0000000000..4c2f043bc2--- /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.tsindex 40f97e6739..ab1263a542 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.");