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

问题描述 投票:0回答:1

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

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

JavaScript 的

Intl
API 对区域设置使用“经典”日期格式
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...”)来使用 Intl 的“现代”(= ISO-8601)日期格式?例如,使用区域设置

de-DE-u-ca-iso8601
不起作用。

顺便说一句:使用

Date.prototype.toISOString
不是一个选项。
[编辑]仅使用不同国家/地区的语言环境也不是一个选项。

[编辑]我希望在这里这里找到答案,但还没有在那里找到解决方案。

[编辑]您可以通过区域设置字符串配置时间格式:

en-GB
(显示24小时时间格式)
en-GB-u-hc-h12
(显示 12 小时时间格式,添加 am/pm)
...所以我希望类似的事情也可以通过“dd.mm.yyyy”与“yyyy-mm-dd”来实现。

javascript date internationalization intl
1个回答
2
投票

使用

en-CA
作为区域设置

据我所知,没有特定的区域设置可以格式化为“现代”(iso)日期字符串。

拆分并重新排序日期字符串,使用

formatToParts
代替
format
或拆分
Date.toISOString
的结果可能是其他想法。

注意(2023 年 11 月):我创建了一个可能有用的小型库 (es-date-fiddler)。

// 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]);

© www.soinside.com 2019 - 2024. All rights reserved.