繁体   English   中英

JavaScript Intl/BCP 47:如何为德语语言环境使用 ISO 日期格式“yyyy-mm-dd”而不是“dd.mm.yyyy”?

[英]JavaScript Intl/BCP 47: How to use ISO date format `yyyy-mm-dd` for German locales instead of `dd.mm.yyyy`?

德国使用两种不同的日期格式:

  • 现代(不经常使用,ISO-8601):2022-01-31
  • 古典(大多数德国人使用):31.01.2022

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM