[英]Convert moment.js to date-fns
I need to convert this from moment.js moment(date, 'DD MM YYYY').isBefore(moment())
to date-fns.我需要将它从 moment.js
moment(date, 'DD MM YYYY').isBefore(moment())
转换为 date-fns。 I tried isBefore(format(value, 'dd-MM-yyyy'), sub(new Date(), { days: 1 }))
.我试过
isBefore(format(value, 'dd-MM-yyyy'), sub(new Date(), { days: 1 }))
。 I mention that now I have to substract 1 day.我提到现在我必须减去 1 天。 So the functionality will be to compare
value
which is the date given with currentDate - 1 day.因此,功能将是比较与 currentDate - 1 天给出的日期的
value
。 Essentially, check if future date is given, (future date includes current day).本质上,检查是否给出了未来日期(未来日期包括当天)。 Hope this is clear enough.
希望这足够清楚。 My example doesn't work and I don't understand why.
我的例子不起作用,我不明白为什么。
Looks like you're using format
instead of parse
.看起来您使用的是
format
而不是parse
。 isBefore
accepts a number
or Date
not a string as its first argument. isBefore
接受number
或Date
而不是字符串作为其第一个参数。
See example:参见示例:
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);
We can run the value against a function that replaces all /
and \s
to -
.我们可以针对将所有
/
和\s
替换为-
的 function 运行该值。
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", new Date()),
sub(new Date(), { 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.