3

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?

RobG
  • 142,382
  • 31
  • 172
  • 209
name
  • 235
  • 2
  • 12

5 Answers5

1

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");
Tamil.S
  • 403
  • 3
  • 14
  • A good answer should explain why the OP has their issue and how your code fixes it. It shouldn't contain syntax errors. – RobG Aug 12 '20 at 06:45
0

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Nessi
  • 276
  • 1
  • 4
  • 23
0

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");
}
Nsevens
  • 2,588
  • 1
  • 17
  • 34
0

You can use the date-fns library for date comparisions.

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

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

isAfter(date1, today);
ChrisG
  • 2,637
  • 18
  • 20
0

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?

RobG
  • 142,382
  • 31
  • 172
  • 209