Javascript Intl.DateTimeFormat hours12 gives odd output on Chrome

二次信任 提交于 2021-02-05 11:34:32

问题


I'm seeing behavior on Chrome where the return value for a 12:00 pm time formatted with hours12 set to true comes out as 0 pm. Shouldn't it be 12? If not, what's the proper way to display a 12 hour clock? Note that I'm constrained to using ES5.

The following in Chrome prints 0 pm:

var foo = new Date(2020, 0, 1, 12, 0, 0)
var bar = new Intl.DateTimeFormat("en-GB", {hour12: true, hour: "numeric"}).format(foo)
console.log(bar)

Note that the value of bar is '0 pm'. Other languages besides en-GB exhibit this behavior. The same code run with en-US, though, gives me '12 PM'. Is it that the British and others actually use '0 pm' to indicate noon? Is this a bug in Chrome? It does not happen in FF or IE.

Thanks in advance for any input.


回答1:


This is likely an issue with hour cycle. It's supposed to be based on the supplied language code and should be overridden by setting the "hc" option to one of "h11", "h12", "h23", "h24".

However, Chrome seems to ignore the hour cycle anyway:

var foo = new Date(2020, 0, 1, 12, 0, 0)
var bar = new Intl.DateTimeFormat("en-GB", {
  hour12: true,
  hour: "numeric",
  hc: "h12" // Should force 12 am / 12 pm
}).format(foo);

console.log(bar); // 0 pm in Chrome, 12 pm in others

According to MDN, if both hour12 and hc options are set, then hour12 takes precedence. However, removing the hour12 option and setting hc:"12" returns just "12", without the "pm" and midnight is "00".

The Intl object doesn't specify what format languages map to, it's left up to individual implementations to work out what a particular language or culture uses. So you can use trial and error to find a language code that does the job, e.g. in this case using just "en" rather than "en-GB" returns 12 pm in Chrome.

As far as I can see, the Intl object is not suitable for formatting dates. It's really only good for conveniently getting the date parts using the formatToParts method then formatting manually from there. It's also handy for getting dates and times in timezones based on IANA locations, but you can't expect it to properly or consistently format dates across different implementations just based on the language code.




回答2:


Not sure if you're still looking for a solution... I had the same problem too but found that using hourCycle: 'h12' worked instead of hour12: true



来源:https://stackoverflow.com/questions/63273543/javascript-intl-datetimeformat-hours12-gives-odd-output-on-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!