diff --git a/src/utils/datetime.ts b/src/utils/datetime.ts new file mode 100644 index 0000000..81ed0bd --- /dev/null +++ b/src/utils/datetime.ts @@ -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; +}