From ba63760f0fd4f12e61c425aa4dfcc6d9aefcd0c5 Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Fri, 26 Apr 2024 09:39:17 +0100 Subject: [PATCH] Display dates in users locale --- packages/bbui/src/helpers.js | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/bbui/src/helpers.js b/packages/bbui/src/helpers.js index 78bd14fe13..fa29d140a0 100644 --- a/packages/bbui/src/helpers.js +++ b/packages/bbui/src/helpers.js @@ -186,6 +186,31 @@ export const stringifyDate = ( } } +// Gets the correct format for a date in a specific locale +const getDateFormatPattern = locale => { + const getPatternForPart = part => { + switch (part.type) { + case "day": + return "D".repeat(part.value.length) + case "month": + return "M".repeat(part.value.length) + case "year": + return "Y".repeat(part.value.length) + case "literal": + return part.value + default: + console.log("Unsupported date part", part) + return "" + } + } + return new Intl.DateTimeFormat(locale) + .formatToParts(new Date("2021-01-01")) + .map(getPatternForPart) + .join("") +} + +const localeDateFormat = getDateFormatPattern(navigator.language || "en-US") + // Formats a dayjs date according to schema flags export const getDateDisplayValue = ( value, @@ -197,8 +222,8 @@ export const getDateDisplayValue = ( if (timeOnly) { return value.format("HH:mm") } else if (!enableTime) { - return value.format("MMMM D YYYY") + return value.format(localeDateFormat) } else { - return value.format("MMMM D YYYY, HH:mm") + return value.format(`${localeDateFormat}, HH:mm`) } }