2024-12-22 22:16:00 +02:00
|
|
|
type DateTimeStyle = "full" | "long" | "medium" | "short" | "none" | undefined;
|
|
|
|
|
|
2024-12-10 17:13:46 +02:00
|
|
|
/**
|
2024-12-10 18:40:24 +02:00
|
|
|
* Formats the given date and time to a string based on the current locale.
|
2024-12-10 17:13:46 +02:00
|
|
|
*/
|
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 "";
|
|
|
|
|
}
|
|
|
|
|
|
2024-12-10 18:09:55 +02:00
|
|
|
const locale = navigator.language;
|
|
|
|
|
|
2024-12-10 18:40:24 +02:00
|
|
|
let parsedDate;
|
2024-12-22 22:16:00 +02:00
|
|
|
if (typeof date === "string" || typeof date === "number") {
|
2024-12-10 18:40:24 +02:00
|
|
|
// Parse the given string as a date
|
|
|
|
|
parsedDate = new Date(date);
|
2024-12-22 22:16:00 +02:00
|
|
|
} else if (date instanceof Date) {
|
2024-12-10 18:48:48 +02:00
|
|
|
// The given date is already a Date instance or a number
|
2024-12-10 18:40:24 +02:00
|
|
|
parsedDate = date;
|
|
|
|
|
} else {
|
2024-12-10 18:48:48 +02:00
|
|
|
// Invalid type
|
|
|
|
|
throw new TypeError(`Invalid type for the "date" argument.`);
|
2025-01-09 18:07:02 +02:00
|
|
|
}
|
2024-12-10 18:40:24 +02:00
|
|
|
|
2024-12-22 22:16:00 +02:00
|
|
|
if (timeStyle !== "none" && dateStyle !== "none") {
|
|
|
|
|
// Format the date and time
|
2025-01-09 18:07:02 +02:00
|
|
|
const formatter = new Intl.DateTimeFormat(navigator.language, { dateStyle, timeStyle });
|
2024-12-22 22:16:00 +02:00
|
|
|
return formatter.format(parsedDate);
|
|
|
|
|
} else if (timeStyle === "none" && dateStyle !== "none") {
|
2024-12-10 18:09:55 +02:00
|
|
|
// Format only the date
|
2025-01-09 18:07:02 +02:00
|
|
|
return parsedDate.toLocaleDateString(locale, { dateStyle });
|
2024-12-22 22:16:00 +02:00
|
|
|
} else if (dateStyle === "none" && timeStyle !== "none") {
|
2024-12-10 18:09:55 +02:00
|
|
|
// Format only the time
|
2025-01-09 18:07:02 +02:00
|
|
|
return parsedDate.toLocaleTimeString(locale, { timeStyle });
|
2024-12-10 18:09:55 +02:00
|
|
|
}
|
2024-12-22 22:16:00 +02:00
|
|
|
|
|
|
|
|
throw new Error("Incorrect state.");
|
2024-12-10 18:09:55 +02:00
|
|
|
}
|