0

In database my date is stored in D/M/YYYY format eq:(7/1/2021)

var todayDate = (
 new Date().getDate() +
  "/" +
  (new Date().getMonth() + 1) +
  "/" +
  new Date().getFullYear()
);
 console.log(todayDate);

shows current date as 14/1/2021 when i compare to know which date is greater it shows false

console.log(todayDate > date);// date stored in database(7/1/2021)

can anyone please solve this and thanks in advance

  • Why not comparing getTime() which represent the mili-seconds since epoch instead of a **string** formatted date comparison? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime – Ofir Baruch Jan 13 '21 at 19:14

1 Answers1

2

you can't compare date strings using ">" operator. if its a string it's comparing them alphabetically.

Instead use date.getTime() to compare.

also, just use toLocalDateString() for date stings, instead of trying to re-invent the wheel yourself.

var todayDate = (new Date().toLocalDateString());
console.log(todayDate);
Rick
  • 1,710
  • 8
  • 17
  • Now i have stored dates as D/M/YYYY how will i compare now. new.Date().toLocalDateString() gives date in MM/DD/YYYY format. I wanted the date in D/M/YYYY formate. – Theophin Johnson Jan 14 '21 at 07:01
  • How to compare dates using date.getTime() to compare date in my code – Theophin Johnson Jan 14 '21 at 07:06
  • 1
    simply create a function that converts your D/M/YYYY string into a date object. then use .getTime() to compare to other dates. The important thing is converting your data into date objects and not comparing them as strings. – Rick Jan 14 '21 at 17:13