Last active
March 23, 2022 12:01
-
-
Save jpzwarte/2f01b07cd79b62e6488565432f59cc6f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type DateParts = { year: string; month: string; day: string }; | |
export function getLocalizedDateParts(locale: string): DateParts { | |
const rtf = new Intl.RelativeTimeFormat(locale), | |
result: DateParts = { year: '', month: '', day: '' }; | |
['year', 'month', 'day'].forEach(part => { | |
const parts = rtf.formatToParts(-1, `${part}s` as Intl.RelativeTimeFormatUnit), | |
index = parts.findIndex(({ unit }) => unit === part), | |
value = parts[index + 1].value; | |
result[part as keyof DateParts] = value.trim().substring(0, 1); | |
}); | |
return result; | |
} | |
export function getLocalizedDatePattern(locale: string, options: Intl.DateTimeFormatOptions = {}): string { | |
const dtf = new Intl.DateTimeFormat(locale, options), | |
parts = getLocalizedDateParts(locale); | |
return dtf | |
.formatToParts(new Date('2022-01-01')) | |
.map(part => { | |
switch (part.type) { | |
case 'day': | |
return parts.day.repeat(part.value.length); | |
case 'month': | |
return parts.month.repeat(part.value.length); | |
case 'year': | |
return parts.year.repeat(part.value.length); | |
default: | |
return part.value; | |
} | |
}) | |
.join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment