Is there a standard way in Javascript to get the localized date format for a given locale?
Here are some examples of what I'm looking for:
fr-FR
->jj/mm/aaaa
en-US
->mm/dd/yyyy
de-DE
->TT.mm.jjjj
- etc.
I got those examples by looking at the placeholder of an <input type="date" />
after changing my browser's locale. So it appears the browser has this data somewhere. Is there a standard JS API or library that makes it accessible?
What I got so far
I can get the non-localized date format by using Intl.DateTimeFormat
's formatToParts
API.
function getDateFormat(locale) {
return new Intl.DateTimeFormat(locale, {
year: "numeric",
month: "2-digit",
day: "2-digit",
})
.formatToParts(new Date())
.reduce((acc, part) => {
const { type, value } = part;
if (type === "year") {
return acc + "YYYY";
} else if (type === "month") {
return acc + "MM";
} else if (type === "day") {
return acc + "DD";
} else {
return acc + value;
}
}, "");
}
This implementation does not account for the placeholder variations related to the locale (for locale fr-FR
, "aaaa"
should be used instead of "YYYY"
, etc.). Currently, I have to perform the mapping myself to get the localized version, which I'd like to avoid.