问题
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