Skip to content

Instantly share code, notes, and snippets.

@jpzwarte
Last active March 23, 2022 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpzwarte/2f01b07cd79b62e6488565432f59cc6f to your computer and use it in GitHub Desktop.
Save jpzwarte/2f01b07cd79b62e6488565432f59cc6f to your computer and use it in GitHub Desktop.
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