Files
Trilium/apps/client/src/utils/formatters.ts

54 lines
1.9 KiB
TypeScript
Raw Normal View History

import options from "../services/options";
type DateTimeStyle = "full" | "long" | "medium" | "short" | "none" | undefined;
/**
* Formats the given date and time to a string based on the current locale.
*/
2025-08-22 18:23:54 +03:00
export function formatDateTime(date: string | Date | number | null | undefined, dateStyle: DateTimeStyle = "medium", timeStyle: DateTimeStyle = "medium") {
if (!date) {
return "";
}
const locale = options.get("formattingLocale") || options.get("locale") || navigator.language;
let parsedDate;
if (typeof date === "string" || typeof date === "number") {
// Parse the given string as a date
parsedDate = new Date(date);
} else if (date instanceof Date) {
// The given date is already a Date instance or a number
parsedDate = date;
} else {
// Invalid type
throw new TypeError(`Invalid type for the "date" argument.`);
2025-01-09 18:07:02 +02:00
}
if (timeStyle !== "none" && dateStyle !== "none") {
// Format the date and time
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
try {
return parsedDate.toLocaleDateString(locale, { dateStyle });
} catch (e) {
return parsedDate.toLocaleDateString(undefined, { dateStyle });
}
} else if (dateStyle === "none" && timeStyle !== "none") {
// Format only the time
try {
return parsedDate.toLocaleTimeString(locale, { timeStyle });
} catch (e) {
return parsedDate.toLocaleTimeString(undefined, { timeStyle });
}
}
throw new Error("Incorrect state.");
}