From 8d23fca9a097861867f7b5c0fc0f3c479f4e7ce3 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 23 Jul 2021 15:47:10 +0200 Subject: [PATCH] Add short format for datetimes Signed-off-by: Thomas Citharel --- js/src/filters/datetime.ts | 57 ++++++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 12 deletions(-) diff --git a/js/src/filters/datetime.ts b/js/src/filters/datetime.ts index 076121d98..4211375f8 100644 --- a/js/src/filters/datetime.ts +++ b/js/src/filters/datetime.ts @@ -21,19 +21,52 @@ function formatTimeString(value: string): string { }); } -function formatDateTimeString(value: string, showTime = true): string { - const options: DateTimeFormatOptions = { - weekday: undefined, - year: "numeric", - month: "long", - day: "numeric", - hour: undefined, - minute: undefined, - }; +// TODO: These can be removed in favor of dateStyle/timeStyle when those two have sufficient support +// https://caniuse.com/mdn-javascript_builtins_intl_datetimeformat_datetimeformat_datestyle +const LONG_DATE_FORMAT_OPTIONS: DateTimeFormatOptions = { + weekday: undefined, + year: "numeric", + month: "long", + day: "numeric", + hour: undefined, + minute: undefined, +}; + +const LONG_TIME_FORMAT_OPTIONS: DateTimeFormatOptions = { + weekday: "long", + hour: "numeric", + minute: "numeric", +}; + +const SHORT_DATE_FORMAT_OPTIONS: DateTimeFormatOptions = { + weekday: undefined, + year: "numeric", + month: "short", + day: "numeric", + hour: undefined, + minute: undefined, +}; + +const SHORT_TIME_FORMAT_OPTIONS: DateTimeFormatOptions = { + weekday: "short", + hour: "numeric", + minute: "numeric", +}; + +function formatDateTimeString( + value: string, + showTime = true, + dateFormat = "long" +): string { + const isLongFormat = dateFormat === "long"; + let options = isLongFormat + ? LONG_DATE_FORMAT_OPTIONS + : SHORT_DATE_FORMAT_OPTIONS; if (showTime) { - options.weekday = "long"; - options.hour = "numeric"; - options.minute = "numeric"; + options = { + ...options, + ...(isLongFormat ? LONG_TIME_FORMAT_OPTIONS : SHORT_TIME_FORMAT_OPTIONS), + }; } const format = new Intl.DateTimeFormat(locale(), options); return format.format(parseDateTime(value));