Javascript date variable issue

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 does not work:

 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) does not work with the above code. Any idea?

0
source share
3 answers

You compare object references using == . Although they can represent the same time and date, they represent different objects. Using < / > works because it passes objects into numbers (milliseconds from an era), which are then compared. If you want to check for equality, you need to force this 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) 
+5
source

you can compare dates using getTime (), for example:

 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/

+1
source

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!"); 
+1
source

All Articles