德国使用两种不同的日期格式:
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)使用
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]);