Intl.DateTimeFormat shows time being 24:59

我与影子孤独终老i 提交于 2020-05-16 07:50:41

问题


Hey everyone| just checking if I am doing something wrong. The code below gives me time = 24:59, in Prague (GMT+1). Using Chrome.

new Intl.DateTimeFormat(
  'en',
  {
     weekday: 'long',
     month: 'long',
     day: 'numeric',
     hour: 'numeric',
     minute: 'numeric',
     hour12: false
  }
 ).format(new Date('2020-03-11T23:59:00Z')
) 
// "Thursday, March 12, 24:59"

When using the .getHours() I will get a correct value of 0 though.

new Date('2020-03-11T23:59:00Z'); // Thu Mar 12 2020 00:59:00 GMT+0100 (Central European Standard Time)
new Date('2020-03-11T23:59:00Z').getHours(); // 0

Thanks for suggestions, I didn't found any related issues about this.

Tomas


回答1:


Your code gives me "Thursday, March 12, 00:59" in Firefox and "Thursday, March 12, 24:59" in Chrome (80.0.3987.149)

There appears to be a bug open for Chrome 80 https://support.google.com/chrome/thread/29828561?hl=en, open since February, but not much is said about whether it will be fixed and how. Consider upvoting it.

According to a comment posted there, you could work around the issue by replacing the hour12 property with hourCycle: 'h23'.

new Intl.DateTimeFormat(
  'en',
  {
     weekday: 'long',
     month: 'long',
     day: 'numeric',
     hour: 'numeric',
     minute: 'numeric',
     hourCycle: 'h23'
  }
 ).format(new Date('2020-03-11T23:59:00Z')
)
// "Thursday, March 12, 00:59"

This seems to do the trick for me




回答2:


The issue seems to be the default setting for HourCylce and langauge en, which you expect to be h23 but Chrome is using h24. You can fix it as described by toniedzwiedz, or you can provide a suitable country code for the language tag to force the HourCylce to default to h23, say GB:

let d = new Date(2020,2,1,0,23);
let opts = {hour12:false, hour: 'numeric'};

console.log(d.toLocaleString('en', opts)); // 24 (Chrome), 00 others
console.log(d.toLocaleString('en-GB', opts)); // 00 all


来源:https://stackoverflow.com/questions/60886186/intl-datetimeformat-shows-time-being-2459

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