-2

I'm trying to compare two same dates in the browser console and getting the result as false. I don't understand how is it comparing as both the dates are the same?

$(function()
{
  var d1 = new Date("01-12-2001");
  var d2 = new Date("01-12-2001");
  
  console.log(d1 == d2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

but here if try to compare with GT and LT then its working.

Carl Binalla
  • 5,393
  • 5
  • 27
  • 46
SPnL
  • 338
  • 4
  • 15
  • 1
    "Working" depends on what you expect as the result. "01-12-2001" is not a format supported by ECMA-262, so parsing is implementation dependent. At least two current browsers will return an invalid date, – RobG Jul 27 '19 at 11:14

3 Answers3

5

It is checking for object equality. Compare the time instead.

$(function()
{
  var d1 = new Date("2001-12-01");
  var d2 = new Date("2001-12-01");
  
  console.log(d1.getTime() == d2.getTime());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
fiveelements
  • 3,649
  • 1
  • 17
  • 16
  • Except that in some browsers the result is `NaN == NaN` which is always false. – RobG Jul 27 '19 at 11:08
  • @RobG OP was comparing two Date objects and expecting true. That won't happen. The suggestion was to compare time. In some browser (IE is one of them) that date pattern is not recognized and hence you get NaN. Surely that has to be handled or the date format needs to be changed to an acceptable one. – fiveelements Jul 27 '19 at 11:13
  • This answer doesn't "work" in Safari or Firefox. It would help the OP to address the parsing issue in the same answer rather than letting them discover it later and have to ask another question. – RobG Jul 27 '19 at 11:19
3

Use numeric value corresponding to the time for the specified date according to universal time.

In your case use this

console.log((new Date("2001-12-01")).getTime() === (new Date("2001-12-01")).getTime());

Edit: The date format for parsing should be YYYY-MM-DD

Govind Sah
  • 116
  • 10
0

You need format new Date() to dateTime string first.

var d1 = new Date("01-12-2001");
var d2 = new Date("01-12-2001");

console.log(d1.toLocaleDateString() == d2.toLocaleDateString());
Chando
  • 424
  • 4
  • 14