![](/img/trans.png)
[英]Reactjs (javascript) how do I not see that the list is empty (Before) api gets called
[英]How do I see if dates came before or after with javascript?
我得到了一个日期const date1 = "2020-08-08"
我想检查这个日期是今天之前还是今天之后
const date1 = "2020-08-08"
const today = new Date()
if(date1 > new Date) {
console.log("date1 is the future")
} else {
console.log("date1 is the past")
}
上面的代码不起作用,但我正在尝试做类似的事情。 有办法吗?
尝试使用 getTime()
var date1 = new Date(2020 - 08 - 08);
var today = new Date();
if (date1.getTime() > today.getTime()) {
// Date 1 is the Future
} else {
// Today is the Future
}
或者你可以直接比较date1 > today
如果您将日期作为字符串,则使用解析,
var date1 = Date.parse("2020-08-08");
您可以今天提取并比较:
var now = new Date();
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var year = now.getFullYear();
var today = year + '-' + month + '-' + day;
您可以分别比较年、月和日并查看。
这是一个可以帮助您入门的工作片段:
let date1 = Date.parse("2020-08-08"); let today = new Date(); if (date1 < today) { console.log("Date1 is in the past"); } else { console.log("Date1 is in the future"); }
您可以使用date-fns
库进行日期比较。
https://date-fns.org/v2.15.0/docs/isBefore
https://date-fns.org/v2.15.0/docs/isAfter
isAfter(date1, today);
在if (date1 > new Date)
中,表达式new Date返回一个字符串,因此您实际上是在比较'2020-08-08' > new Date().toString()
。 由于两个操作数都是字符串,它们将在词法上进行比较,并且由于左侧字符串以数字开头,右侧字符串始终以字母开头,因此结果将始终为 false。
你可能的意思是:
const date1 = "2020-08-08";
const today = new Date();
if (date1 > today) {
console.log("date1 is the future");
}
但是,“2020-08-08”将被解析为 UTC,因此在 8 月 8 日,测试可能会返回 true 或 false,具体取决于主机系统偏移设置和代码执行时间。 请参阅为什么 Date.parse 给出不正确的结果?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.