[英]JavaScript Intl/BCP 47: How to use ISO date format `yyyy-mm-dd` for German locales instead of `dd.mm.yyyy`?
德国使用两种不同的日期格式:
JavaScript 的Intl
API 对 locale de-DE
使用“经典”日期格式:
// This prints out: 31.01.2022
console.log(new Intl.DateTimeFormat('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).format(new Date(2022, 0, 31)));
请在此处找到演示: » 演示
是否可以通过扩展上面示例中的语言环境('de-DE ...')将“现代”(= ISO-8601)日期格式与 Intl 一起使用? 例如,使用语言环境de-DE-u-ca-iso8601
是行不通的。
顺便说一句:使用Date.prototype.toISOString
不是一个选项。
[编辑] 仅使用不同国家/地区的语言环境也不是一种选择。
[编辑] 我希望在这里或这里找到答案,但还没有找到解决方案。
[编辑] 您可以通过语言环境字符串配置时间格式:
en-GB
(显示 24 小时制时间格式)
en-GB-u-hc-h12
(显示 12 小时制,添加上午/下午)
...所以我希望“dd.mm.yyyy”与“yyyy-mm-dd”也可以实现类似的东西。
使用
。en-CA
作为 locale
Afaik 没有特定的语言环境可以格式化为“现代”(iso)日期字符串。
拆分和重新排序日期字符串,使用formatToParts
而不是format
或拆分Date.toISOString
的结果可能是其他想法。
// 1. locale 'en-CA' (not an option as per comment) console.log(new Intl.DateTimeFormat(`en-CA`, { year: `numeric`, month: `2-digit`, day: `2-digit`}).format(new Date(2022, 0, 31))); // 2. split and reorder the result console.log(new Intl.DateTimeFormat(`de-DE`, { year: `numeric`, month: `2-digit`, day: `2-digit`}).format(new Date(2022, 0, 31)).split(`.`).reverse().join(`-`) ); // 3. use formatToParts const reformatGerman = new Intl.DateTimeFormat(`de-DE`, { year: 'numeric', month: '2-digit', day: '2-digit'}).formatToParts(new Date(2022, 0, 31)).filter( v => ~[`year`, `month`, `day`].indexOf(v.type) ).reduce( (acc, val) => ({...acc, [val.type]: val.value}), {} ); console.log(`${ reformatGerman.year}-${ reformatGerman.month}-${ reformatGerman.day}`); // 4. truncate the result of `toISOString()` console.log(new Date(Date.UTC(2022, 0, 31)).toISOString().split(`T`)[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.