How to compare two dates via javascript?

How to compare two dates via java-script or how to check two dates that which one is greater and smaller?
here is a code where you can check that which date is greater then other or same as vice verse.
Simply copy and paste below code in your html file and run the file and change variable according to your need.
Note: date format can be in two format one 2012-12-26 00:00:00  or 2012/12/26 00:00:00



Date compare
<script>
var s_date1 = "2012-12-26 00:00:00";
var en_date1 = "2012-12-26 00:00:00";
var s_date1_new=s_date1.replace(/-/g,"/"); // this line is for if date format is in hyphen like  2013-12-12 00:00:00
var en_date1_new=en_date1.replace(/-/g,"/"); // this line is for if date format is in hyphen like  2013-12-12 00:00:00

var date_ini = new Date(s_date1_new).getTime();
var date_end = new Date(en_date1_new).getTime();


if(isNaN(date_ini)) {
alert("Start date format is wrong!");
return false;
}
if(isNaN(date_end)) {
// error date_end;
alert("End date format is wrong!");
return false;

}
if(date_ini > date_end) {
// do something;
alert("Start date can not be greater than end date!");
return false;
}

if(date_ini == date_end) {
// do something;
alert("Both date can not be equal!");
return false;

}
</script>

Comments

  1. I want to say that this article is awesome, nice written and include approximately all vital info. I’d like to see more posts like this .

    ReplyDelete
  2. Perfect solution to my problem today!
    Good Work
    ~Cheers

    ReplyDelete

Post a Comment