0

I have two dates .

var dateOne = "24/04/1995"
var dateTwo = "24/04/1998"

How can i check if one date is bigger than the other?

I tried this :

function myFunction() {
  
    var d1 = Date.parse(dateOne);
    var d2 = Date.parse(dateTwo);
    if (d1 < d2) {
    alert ("Error! Date did not Match");
     }
}

but its not working =(

there is a method for this dd/mm/yyyy format?

yanir midler
  • 2,153
  • 1
  • 4
  • 16
  • 1
    Relying on `Date.parse` for dd/MM/yyyy format is a bad idea. Read [this fully](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) – Jamiec Aug 25 '21 at 08:03
  • Also see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Aug 25 '21 at 08:31

2 Answers2

2

Relying on the docs around Date

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

You can simply cast to a Number and compare:

const isDateOneBigger = +dateOne > +dateTwo;

However in your case your Dates are invalid. You can check this by logging out d1 which will result in NaN. If you take a look at How to convert dd/mm/yyyy string into JavaScript Date object? you'll see how you can convert your strings into correct dates.

Ian
  • 33,605
  • 26
  • 118
  • 198
  • @T.J.Crowder I hadn't realised that but you're very much correct! – Ian Aug 25 '21 at 08:03
  • 1
    *(I deleted my earlier comment, sorry didn't realize you'd replied.)* `<` will do that implicitly. The real problem with the OP's code is relying on parsing that date format. – T.J. Crowder Aug 25 '21 at 08:04
  • @T.J.Crowder yep I've just worked that out. I'm going to update my answer to accommodate that – Ian Aug 25 '21 at 08:05
  • This is an **often** repeated duplicate, there's really no need for answers here. :-) – T.J. Crowder Aug 25 '21 at 08:05
0

use the getTime() as so

function myFunction() {
  
    var d1 = new Date(dateOne);
    var d2 = new Date(dateTwo);
    if (d1.getTime() < d2.getTime()) {
    alert ("Error! Date did not Match");
     }
}

the getTime() method convert the date into milliseconds

  • @T.J.Crowder thanks for the info i didnt know that actually – fodil yacine Aug 25 '21 at 08:03
  • *(I deleted my earlier comment, sorry didn't realize you'd replied.)* `<` will do that implicitly. The real problem with the OP's code is relying on parsing that date format. – T.J. Crowder Aug 25 '21 at 08:04
  • This is just a different formulation of the OP code with the same error: using the built–in parser for an unsupported format (or using the built–in parser at all). – RobG Aug 25 '21 at 08:34