I want my webpage to display date and time in user's locale.
It seems Intl
is supported by most browsers now (see Can I Use Intl). I can acquire browser time zone just fine by using Intl.DateTimeFormat().resolvedOptions().timeZone
. I hoped I will be able to emit a date-time using my current locale, by doing:
var date = new Date(2017, 11, 31, 23, 59, 59);
var format = new Intl.DateTimeFormat(
undefined, // locale
{
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
}
)
console.log(format.format(date))
I am using Chrome on Windows. My Windows OS locale is set as "Czech Republic". My preferred site language is set to "Czech" in Chrome, however the browser itself is is set to use US English.
With those settings the output is done in 12 H format, as if my locale was en-us
. As soon as I switch my Chrome browser to use Czech as its presentation language, the time switches to 24 format.
I think I must be missing something obvious - is webpage really unable to use the locale user is using, or is this some bug or incompleteness in Chrome Intl implementation?
I found following is more reliable on Chrome: one can use navigator.languages[0]
to get the locale defined by the language the user is preferring for the content. See also Best way to determine user's locale within browser for a discussion regarding browser compatibility.
function getLocale() {
return (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.language;
}
var locale = getLocale();
var date = new Date(2017, 11, 31, 23, 59, 59);
var format = new Intl.DateTimeFormat(
locale,
{
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
}
)
console.log(format.format(date))
Still it seems a shame one cannot access the system wide choice of locale the user has made.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With