在
moment
中,我可以使用下面的代码来格式化可能具有不同格式样式的日期字符串。
let test=['2022-04-29', '04-29-2022','29-04-2022', '4/29/2022', '29/4/2022']
test.forEach((value)=>{
const dateFormats = ['MM-DD-YYYY', 'DD-MM-YYYY', 'YYYY-MM-DD', 'YYYY-DD-MM'];
console.log( moment(value, dateFormats).format('MM-DD-YYYY'));
});
所有日期字符串都可以正确解析。
当用
moment
替换date-fns
时,我没有找到好的方法。 parse
仅接受一种日期格式字符串。test(){
let test=['2022-04-29', '04-29-2022','29-04-2022', '4/29/2022', '29/4/2022']
test.forEach((value)=>{
const formatStyle = this.GetDateFormat(value);
if(!formatStyle) {
return 'Invalid Date';
}
const temp = parse(value, formatStyle, new Date());
console.log(format(temp, 'MM-dd-yyyy'));
});
}
dateFormatArray = ['MM-dd-yyyy', 'MM/dd/yyyy', 'MM.dd.yyyy',
'dd-MM-yyyy', 'dd/MM/yyyy', 'dd.MM.yyyy',
'yyyy-MM-dd', 'yyyy/MM/dd', 'yyyy.MM.dd',
'yyyy-dd-MM', 'yyyy/dd/MM','yyyy.dd.MM']
GetDateFormat(date:string):string{
let format ='invalid';
this.dateFormatArray.forEach((dateFormat) => {
if(isMatch(date, dateFormat)){
format = dateFormat;
}
});
return format;
}
还有其他更好的方法来解析
date-fns
中包含不同格式样式的日期字符串吗?
您可以尝试使用不同的库
date-fns-tz
来使用这样的日期字符串...或者您可以使用dateRegexes
在date-fns
中实现相同的效果
import { zonedTimeToUtc } from 'date-fns-tz';
const test=['2022-04-29', '04-29-2022','29-04-2022', '4/29/2022', '29/4/2022'];
test.forEach((value) => {
const dateFormats = ['MM-DD-YYYY', 'DD-MM-YYYY', 'YYYY-MM-DD', 'YYYY-DD-MM'];
const date = dateFormats.reduce((acc, format) => acc || zonedTimeToUtc(value, format), null);
if (date) {
console.log(format(date, 'MM-dd-yyyy'));
} else {
console.log('Invalid Date');
}
});
希望这有帮助...
让一切保持简单:
const time_formats = ['HH.mm', 'HH:mm', 'HH mm'];
const formatted_time = time_formats.map(t => parse(time, t, new Date())).find(t => isValid(t));