feat: add datetime utils
This commit is contained in:
parent
48661a9259
commit
bd75a76ffd
1 changed files with 41 additions and 0 deletions
41
src/utils/datetime.ts
Normal file
41
src/utils/datetime.ts
Normal 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue