如何使用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");

下面是一个开始使用的工作片段:

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);

您今天可以提取并比较:

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;

您可以分别比较年份、月份和日期,然后查看。

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给出错误的结果

最新更新