Search code examples
javascriptjquerydatedate-comparison

Comparing two dates in jquery script


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.


Solution

  • 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>