0
var dt_from = "2013/05/25";
var dt_to   = "2013/05/25";

if(dt_from == dt_to)
{
    alert("Both dates are Equal!");
}
else if(dt_from > dt_to)
{
    alert("From date should not be greater than todate!");
}
else if(dt_from < dt_to)
{
    alert("Okay!");
}

The above Code is working fine. But the following code is not working:

var dt_from = new Date("2013/05/25");
var dt_to   = new Date("2013/05/25");

if(dt_from === dt_to)
{
    alert("Both dates are Equal!");
}
else if(dt_from > dt_to)
{
    alert("From date should not be greater than todate!");
}
else if(dt_from < dt_to)
{
    alert("Okay!");
}

This if(dt_from === dt_to) is not working with the above code. Any Idea?

Cronco
  • 590
  • 6
  • 18
Dylan
  • 137
  • 1
  • 2
  • 10

3 Answers3

5

You are comparing object references with ==. While they may represent the same datetime, they are distinct objects. Using </> works as it casts the objects to numbers (milliseconds since epoch) which are then compared. If you want to test on equality, you have to force that conversion manually:

dt_from.getTime() == dt_to.getTime() // most explicit
// or
+dt_from == +dt_to // shortest
dt_from - dt_to == 0  // equivalent…
dt_from.valueOf() == dt_to.valueOf()
Number(dt_from) == Number(dt_from)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks. I understand that if we are using variable like var dt_from = "2013/05/25"; this quality comparison is working because they are value types but not if we are using var dt_from = new Date("2013/05/25"); because we are using reference types? – Dylan Jun 01 '13 at 14:49
  • Exactly - strings vs. objects. – Bergi Jun 01 '13 at 15:15
1

you could compare dates using getTime(), like this:

var a = new Date("2013/05/25");
var b = new Date("2013/05/25");

//compare dates
alert(a.getTime() === b.getTime())

working example: http://jsfiddle.net/HrJku/

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
1

Two Dates are never identical, even if they refer to the same point in time. You need to convert them to strings or numbers, You can subtract one from the other, for example:

var dt_from= new Date("2013/05/25");
var dt_to= new Date("2013/05/25");
var diff= dt_to-dt_from;


if(diff=== 0){
    alert("Both dates are Equal!");
}
else if(diff<0){
    alert("From date should not be greater than todate!");
}
else alert("Okay!");
kennebec
  • 102,654
  • 32
  • 106
  • 127