如何使用Intl.DateTimeFormat API格式化毫秒



我需要在特定的区域设置中格式化时间戳(不是utc,也不是浏览器区域设置(。但我也必须有日期的毫秒部分。我的第一次尝试是使用DateTimeFormatAPI的second:'numeric'

new Intl.DateTimeFormat(
'de-de', // german as an example, user selectable
{ 
year: 'numeric', month: 'numeric',  day: 'numeric', 
hour: 'numeric', minute: 'numeric', 
second: 'numeric',
hour12: false
}
)
.format(new Date()); // Date as an example

但结果类似于"26.11.2018, 09:31:04"而不是"26.11.2018, 09:31:04,243"

有没有比使用formatToParts()检测丢失的毫秒并使用Intl.NumberFormat再次添加它更容易的可能性?

注意:如果有人需要实现这一点,Microsoft浏览器会在输出中添加从左到右标记的Unicode字符。因此,在不进行清理的情况下,您无法parseInt来自formatToParts()的结果。

编辑:将问题移至https://github.com/tc39/ecma402/issues/300

这已经在Chrome和Firefox中指定并实现:

https://github.com/tc39/ecma402/issues/300

https://caniuse.com/mdn-javascript_builtins_intl_datetimeformat_datetimeformat_options_parameter_options_fractionalseconddigits_parameter

new Date().toLocaleString('de-de', { year: 'numeric', month: 'numeric',  day: 'numeric', 
hour: 'numeric', minute: 'numeric', 
second: 'numeric',
fractionalSecondDigits: 3
}
)
// or
new Intl.DateTimeFormat(
'de-de', // german as an example, user selectable
{ 
year: 'numeric', month: 'numeric',  day: 'numeric', 
hour: 'numeric', minute: 'numeric', 
second: 'numeric', fractionalSecondDigits: 3,
hour12: false
}
)
.format(new Date());
// => "6.1.2021, 12:30:52,719"

最新更新