我想要的只是将以德语收到的日期值转换为英语格式,我尝试使用如下所示的时刻库
它确实进行了转换,但不幸的是返回了错误的值。
moment('Mär 29, 2024', 'MMM DD, YYYY', 'de-DE').locale('en-US').format('MM/DD/YYYY')
// Expected Value - 03/29/2024
// received value - 01/29/2024
这个问题有解决办法吗?
您可以使用 Intl API 简单地替换月份名称。
这个小函数应该支持几乎所有这样格式的日期。
function convertLocalizedDateStringToDateObject(strToParse, from) {
for (let i = 0; i < 12; i++) {
const date = new Date(new Date().getFullYear(), i, 1);
const short = date.toLocaleDateString(from, { month: "short" });
const long = date.toLocaleDateString(from, { month: "long" });
const shortReplace = date.toLocaleDateString("en-US", { month: "short" });
const longReplace = date.toLocaleDateString("en-US", { month: "long" });
const shortMonth = strToParse.replace(short, shortReplace);
const longMonth = strToParse.replace(long, longReplace);
if (!isNaN(new Date(shortMonth).valueOf())) {
return new Date(shortMonth);
} else if (!isNaN(new Date(longMonth).valueOf())) {
return new Date(longMonth);
}
}
return new Date(NaN);
}
// March in Germany is März
console.log(convertLocalizedDateStringToDateObject("Mär 29, 2024", "de-DE"));
console.log(convertLocalizedDateStringToDateObject("24. Dezember 2024", "de-DE"));
// January in Austria is Jänner
console.log(convertLocalizedDateStringToDateObject("Jän 2, 2024", "de-AT"));
console.log(convertLocalizedDateStringToDateObject("7. Jänner 2024", "de-AT"));