简体   繁体   English

如何查看日期是在 javascript 之前还是之后?

[英]How do I see if dates came before or after with javascript?

I'm given a date const date1 = "2020-08-08"我得到了一个日期const date1 = "2020-08-08"

I want to check whether this date is before today or after today我想检查这个日期是今天之前还是今天之后

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")
}

The above code doesn't work but I am trying to do something like that.上面的代码不起作用,但我正在尝试做类似的事情。 Is there a way?有办法吗?

Try using getTime()尝试使用 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
}

or you can compare directly like date1 > today或者你可以直接比较date1 > today

If you have date as string, then parse using,如果您将日期作为字符串,则使用解析,

var date1 = Date.parse("2020-08-08");

You can extract today and compare:您可以今天提取并比较:

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;

You can compare year, month and day separately and see.您可以分别比较年、月和日并查看。

Here's a working snippet to get you started:这是一个可以帮助您入门的工作片段:

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

You can use the date-fns library for date comparisions.您可以使用date-fns库进行日期比较。

https://date-fns.org/v2.15.0/docs/isBefore https://date-fns.org/v2.15.0/docs/isBefore

https://date-fns.org/v2.15.0/docs/isAfter https://date-fns.org/v2.15.0/docs/isAfter

isAfter(date1, today);

In if (date1 > new Date) the expression new Date returns a string, so you're effectively comparing '2020-08-08' > new Date().toString() .if (date1 > new Date)中,表达式new Date返回一个字符串,因此您实际上是在比较'2020-08-08' > new Date().toString() Since both operands are strings, they will be compared lexically and since the lefthand string starts with a number and the righthand string will always start with a letter, the result will always be false.由于两个操作数都是字符串,它们将在词法上进行比较,并且由于左侧字符串以数字开头,右侧字符串始终以字母开头,因此结果将始终为 false。

What you probably mean to do is:你可能的意思是:

const date1 = "2020-08-08";
const today = new Date();
if (date1 > today) {
    console.log("date1 is the future");
}

However, '2020-08-08' will be parsed as UTC, so on 8 August the test may return true or false depending on the host system offset setting and the time that the code is executed.但是,“2020-08-08”将被解析为 UTC,因此在 8 月 8 日,测试可能会返回 true 或 false,具体取决于主机系统偏移设置和代码执行时间。 See Why does Date.parse give incorrect results?请参阅为什么 Date.parse 给出不正确的结果?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM