我想根据给定的本地 ID 获取日期的标准日期格式(如 MM/DD/YYYY)。但下面的代码没有给出格式。请帮助我如何获取日期格式。
var dateFormat = new Intl.DateTimeFormat("as-IN").
我所做的是首先根据区域设置格式化一个虚拟日期。然后,我将用标准占位符
DD
、MM
、YYYY
替换不同的日期部分(日、月、年)。
这是代码:
/**
* Returns date format used by Intl.DateTimeFormat (for specified `options`).
* Example for Serbia: `DD/MM/YYYY`
*
* **Note** that this will always return the two decimal format for day and month and four for year (e.g. `DD/MM/YYYY`)
*/
export function getIntlDateFormatForLocale(locale: string, options?: Intl.DateTimeFormatOptions) {
const year = 2222
const month = 12
const day = 15
const date = new Date(year, month - 1, day)
const formattedDate = new Intl.DateTimeFormat(locale, options).format(date)
return formattedDate.replace(`${year}`, 'YYYY').replace(`${month}`, 'MM').replace(`${day}`, 'DD')
}
请注意您从中获得的格式适用于日期部分的两位数表示。这意味着如果用户设置了一位数的区域设置,则使用此格式将生成两位数的日期部分。
例如:如果用户区域设置输出类似
1/1/2021
的日期,则在使用此函数中的格式时,它将被格式化为 01/01/2021
。
当格式输出工作日(例如
Mon
)、普通话/日语/阿拉伯数字等时,它也将无法正常工作
可能还有其他一些注意事项,但对于我的用例来说,这已经足够好了;)
这是一个非常基本的循环,返回远程感知区域设置:
let longDateFormat ='';
for(let i=0;i<new Intl.DateTimeFormat(navigator.language).formatToParts().length;i++){
if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "year") {
longDateFormat += "yyyy";
} else if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "literal"){
longDateFormat += new Intl.DateTimeFormat(navigator.language).formatToParts()[i].value;
} else if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "day") {
longDateFormat += "dd";
} else if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "month") {
longDateFormat += "MM";
}
}
console.log(longDateFormat);