41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
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;
|
|
}
|