问题描述
我需要将它从 moment.js moment(date,'DD MM YYYY').isBefore(moment())
转换为 date-fns。
我试过isBefore(format(value,'dd-MM-yyyy'),sub(new Date(),{ days: 1 }))
。我提到现在我必须减去1天。
因此,该功能将比较 value
与 currentDate - 1 天给出的日期。
本质上,检查是否给出了未来日期(未来日期包括当前日期)。
希望这已经足够清楚了。我的例子不起作用,我不明白为什么。
解决方法
看起来您使用的是 format
而不是 parse
。 isBefore
接受 number
或 Date
而非字符串作为其第一个参数。
参见示例:
function compareDate(value: string) {
return isBefore(
parse(value,'dd-MM-yyyy',new Date()),sub(new Date(),{ days: 1 })
);
}
const test = compareDate('31-12-2020');
console.log(test);
在评论中要求
我们可以针对将所有 /
和 \s
替换为 -
的函数运行该值。
function unifyDateString(value: string) {
try {
return value.split("/").join("-").split(" ").join("-");
} catch {
return value;
}
}
function compareDate(value: string) {
return isBefore(
parse(unifyDateString(value),"dd-MM-yyyy",{ days: 1 })
);
}
const one = compareDate("31-12-2020");
const two = compareDate("31/12/2020");
const three = compareDate("31 12 2020");
console.log(one);
console.log(two);
console.log(three);