Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 624
name Avatar asked Nov 30 '25 03:11

name


1 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");
like image 63
Tamil.S Avatar answered Dec 02 '25 18:12

Tamil.S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!