Search code examples
javascriptdatedate-comparison

Date comparison operator - logical issue


I have this simple js function:

function checkTime() {  
  var d1 = new Date();
  var d2 = new Date('April 10, 2017 12:11:00');

  if (d1 < d2) {
    $('#modalnew').modal('show');
  } else {
    window.location.replace('https://www.example.php');
  }
}

It works fine, but I don't understand the date comparison. This may be a "dumb" question, but I can't find answers on google. F.E.: - no code, just an example -

d1 (now) = April 10, 2017 12:22:00
d2 (date set) = April 10, 2017 12:11:00

Why is the d1 less than d2 and activates the window.location? In a logical order d1 it is 11 minutes greater than d2. On which parameter does it exactly compare?


Solution

  • In your case d1 is not less but more than d2 which is the expected result and hence the window.location.replace is executed .

    While comparing the date it evaluates to if (d1.valueOf()< d2.valueOf()) . valueOf() delivers time in milliseconds since beginning of 00:00:00 UTC Thursday 1, January 1970 and then compares it.