1

i want to compare two dates. i used this code

function addRow(dateval,bidchekval) {                       
    var val1 = document.getElementById(dateval);            

   var valcheck=document.getElementById(bidchekval).value;
   var val123=document.getElementById(dateval).value;

   if(val123 > valcheck ){
       alert("success");
   }
}

This is the code that i used but when change month then it will break.those two dates get using date picker. date format example:06-12-2013 15:12:15

binil
  • 41
  • 1
  • 2
  • 6

2 Answers2

4
if((new Date(val123).getTime()) > (new Date(valcheck).getTime()) ){
       alert("success");
   }
Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37
  • 1
    `.getTime()` is technically faster than `>` `<` comparisons operators that call the `ToPrimitive` algorithm on the Date objects. With `.getTime()`, `==`/`===` comparisons will also work, which do not work when comparing 2 Date objects. – Fabrício Matté Jun 04 '13 at 09:35
  • Thanks for the info, Fabricio! I did it because i always work with milliseconds when dealing with date/time. – Mukesh Soni Jun 04 '13 at 09:36
  • Though it is a bit in this case, I believe `.getTime()` is more clear as it shows what actually happens - the comparison happens between the 2 timestamps from those Date objects. (this conversion would be implicit otherwise) – Fabrício Matté Jun 04 '13 at 09:37
2

You cannot compare strings, but you can compare Date objects.

var valcheck=document.getElementById(bidchekval).value;
var val123=document.getElementById(dateval).value;

var check = new Date(valcheck) ;
var check123 = new Date(val123) ;

if (check > check123){
  alwer("Success") ;
}
sybear
  • 7,837
  • 1
  • 22
  • 38