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

Hol*_*min 6 javascript localization

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

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
Run Code Online (Sandbox Code Playgroud)

但结果是类似"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

Hol*_*min 7

现在 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"
Run Code Online (Sandbox Code Playgroud)