feat: add datetime utils

This commit is contained in:
Methapon2001 2025-01-22 14:48:39 +07:00
parent 48661a9259
commit bd75a76ffd

41
src/utils/datetime.ts Normal file
View file

@ -0,0 +1,41 @@
export function dateFormat(opts: {
date: string | Date | null;
locale?: string;
dayStyle?: "numeric" | "2-digit";
monthStyle?: "numeric" | "2-digit" | "long" | "short";
timeStyle?: "full" | "long" | "medium" | "short";
timeOnly?: boolean;
noDay?: boolean;
noMonth?: boolean;
noYear?: boolean;
withTime?: boolean;
}): string {
const dt = opts.date ? new Date(opts.date) : new Date();
if (opts.timeOnly) {
opts.noDay = true;
opts.noMonth = true;
opts.noYear = true;
opts.timeStyle = opts.timeStyle || "short";
}
let timeText = opts.withTime
? " " +
dateFormat({
date: opts.date,
timeOnly: true,
timeStyle: opts.timeStyle,
})
: "";
if (timeText) opts.timeStyle = undefined;
let formatted = new Intl.DateTimeFormat(opts.locale, {
day: opts.noDay ? undefined : opts.dayStyle || "numeric",
month: opts.noMonth ? undefined : opts.monthStyle || "short",
timeStyle: opts.timeStyle,
year: opts.noYear ? undefined : "numeric",
}).format(dt);
return formatted + timeText;
}