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

Viewed 586

I'm given a date 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?

5 Answers

Try using 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

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

In if (date1 > new Date) the expression new Date returns a string, so you're effectively comparing '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.

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. See Why does Date.parse give incorrect results?

Related