我从服务器获取区域设置,并尝试根据此区域设置格式选项和其他选项来格式化给定日期。它适用于所有语言环境,但 it-CH
date = new Date(2010,0,1)
new Intl.DateTimeFormat('it-CH', {day:'2-digit', month:'2-digit', year:'numeric'}).format(date)
// output: "01.01.2010"
正确的输出应该是01/01/2010
它适用于语言环境it
:
new Intl.DateTimeFormat('it', {day:'2-digit', month:'2-digit', year:'numeric'}).format(date)
// output: "01/01/2010"
或者如果我不在选项中包含年份格式,则使用区域设置 it-CH
:
new Intl.DateTimeFormat('it-CH', {day:'2-digit', month:'2-digit'}).format(date)
// output: "01/01"
正确的输出应该是01/01/2010
。我在 Window 和 Mac OS 上的最新版本的 Chrome 中对其进行了测试。
这种奇怪的行为从何而来,我该如何解决它?
最佳答案
可以通过使用 intl polyfill 模块完全替换 NodeJS 对 intl 的实现来解决这个问题。
首次运行npm i --save intl
然后需要用polyfill替换Intl:
Intl = require("intl")
就是这样。现在您可以尝试:
const date = new Date();
const options = {
year: 'numeric',
day: 'numeric',
month: 'numeric',
hour: 'numeric',
minute: 'numeric'
};
const dateFormatted = new Intl.DateTimeFormat('pt-BR', options).format(date);
console.log(dateFormatted);
//预期输出:24/09/2019 17:43
关于javascript - 具有格式选项的 Intl.DateTimeFormat() 不适用于 'it-CH',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797070/