Javascript: Firefox ignores dateStyle and timeStyle options in both Date.toLocaleString and Intl.DateTimeFormat

梦想的初衷 提交于 2021-01-29 22:28:51

问题


console.log(Intl.DateTimeFormat(undefined, {timeStyle: "long", dateStyle: "long"}).format());

Chrome says: "February 13, 2020 at 7:33:18 PM EST".

Firefox says: "2/13/2020"

Firefox also ignores dateStyle and timeStyle when using toLocaleString.

var date = new Date();
console.log(date.toLocaleString(undefined, {timeStyle: "short", dateStyle: "short"}));
console.log(date.toLocaleString(undefined, {timeStyle: "medium", dateStyle: "medium"}));
console.log(date.toLocaleString(undefined, {timeStyle: "long", dateStyle: "long"}));

All of these lines give the same result in Firefox: "2/13/2020, 8:04:11 PM". Chrome correctly gives different values.

What's going on? How do I get a locale-correct date string in Firefox?

Edit: Apparently Firefox doesn't support these properties.


回答1:


The dateStyle and timeStyle options are still at proposal state (stage 3).

Browsers are not forced to implement it yet, and may very well want to wait for the specs to stabilize before implementing this.

For the time being, you can still use the default options to get a less natural but still localized result:

const supports = testDateTimeStyleSupport();

const opts = supports ? { dateStyle: "long", timeStyle: "long" } : {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
}

console.log( new Intl.DateTimeFormat( undefined, opts ).format() );

// assumes both are supported or none
function testDateTimeStyleSupport() {
  let support = false;
  const tester = {
    get dateStyle() { support = true; }
  };
  new Intl.DateTimeFormat( undefined, tester );
  return support;
}


来源:https://stackoverflow.com/questions/60218476/javascript-firefox-ignores-datestyle-and-timestyle-options-in-both-date-tolocal

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