我有这个代码示例:
function compareDate(value: string) {
return isBefore(
parse(value, 'dd-MM-yyyy', new Date()),
sub(new Date(), { days: 1 })
);
}
const test = compareDate('31-12-2020');在parse()中,我不仅需要使用dd-MM-yyyy,还需要使用dd/MM/yyyy和dd MM yyyy。我如何才能做到这一点?该值将具有用户键入的日期,类型为字符串,看起来像上面的例子。
发布于 2021-05-21 22:43:39
将所有可能的分隔符替换为正确的分隔符:
function compareDate(value: string) {
return isBefore(
parse(value.replace(/[\/ ]/g, '-'), 'dd-MM-yyyy', new Date()),
sub(new Date(), { days: 1 })
)
}
const test = compareDate('31-12-2020')发布于 2021-05-21 22:43:56
您可以使用isMatch来确定您拥有的字符串:
function compareDate(value: string) {
let start;
if (isMatch(value, 'dd-MM-yyyy')) {
start = parse(value, 'dd-MM-yyyy', new Date());
} else if (isMatch(value, 'dd/MM/yyyy')) {
// etc...
}
return isBefore(
start,
sub(new Date(), { days: 1 })
);
}https://stackoverflow.com/questions/67638968
复制相似问题