-1

I am trying to compare old date with today's date but I am not getting output true. Please help me.

let today = new Date(); // 2021-02-13T13:28:28.501Z

if ("2020-11-04T08:01:25.698Z" < today){
    console.log("True");
}
BB Mevada
  • 45
  • 7
  • 4
    Does this answer your question? [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Mike Malyi Feb 13 '21 at 13:34

5 Answers5

0

Variable today is a date object you need to compare it with date object only and then only you will get the desired results

if (new Date() === today ) console.log('true')```
Mike Malyi
  • 983
  • 8
  • 18
kaps_rocks
  • 18
  • 5
0

You can compare two dates (Date objects) using getTime method

console.log(date1.getTime() > date2.getTime())

This example prints true if date1 is later than date2

In your case:

let today = new Date();
let otherDay = new Date("2020-11-04T08:01:25.698Z");

if (otherDay.getTime() < today.getTime()){
    console.log("True");
}
0

You need to convert string to date first

if (new Date("2020-11-04T08:01:25.698Z") < today){
    console.log("True");
}
cbrox
  • 21
  • 4
0
let today = new Date(); // 2021-02-13T13:28:28.501Z 
    if (new Date("2020-11-04T08:01:25.698Z") < today)
    {
     console.log("True"); 
    }

Convert string to Date object and compare.

Ayaz
  • 2,111
  • 4
  • 13
  • 16
0

you can create an isTodaySameDay function and call it. check out the snippet code below:

const isTodaySameDay = (day) => {
    const today = new Date();
    return day.getFullYear() === today.getFullYear() &&
    day.getMonth() === today.getMonth() &&
    day.getDate() === today.getDate();
};

let yesterday = new Date();

yesterday.setDate(yesterday .getDate() - 1);
console.log(isTodaySameDay(yesterday)); //false

let today = new Date();
console.log(isTodaySameDay(today)); //true
Ran Turner
  • 14,906
  • 5
  • 47
  • 53