5

Possible Duplicate:
Compare dates with JavaScript

I have two dates, start date and end date. I am comparing them like this:

var fromDate = $("#fromDate").val();
var throughDate = $("#throughDate").val();

if (startdate >= enddate) {
    alert('start date cannot be greater then end date')
}

It gives the correct result... the only problem is when I compare the dates 01/01/2013 and 01/01/2014.

How can I correctly compare dates in JavaScript?

Community
  • 1
  • 1
user1657872
  • 61
  • 1
  • 1
  • 2

3 Answers3

7

You can use this to get the comparison:

if (new Date(startDate) > new Date(endDate)) 

Using new Date(str) parses the value and converts it to a Date object.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
3

You are comparing strings. You need to convert them to dates first. You can do so by splitting your string and constructing a new Date

new Date(year, month, day [, hour, minute, second, millisecond])

Depending on you date format it would look like

var parts = "01/01/2013".split("/");
var myDate = new Date(parts[2], parts[1] - 1, parts[0]);
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
0
        var fromDate = $("#fromDate").val();
      var toDate = $("#throughDate").val();

    //Detailed check for valid date ranges
        //if your date is like 09-09-2012
    var frommonthfield = fromDate.split("-")[1];
    var fromdayfield = fromDate.split("-")[0];
    var fromyearfield = fromDate.split("-")[2];


    var tomonthfield = toDate.split("-")[1];
    var todayfield = toDate.split("-")[0];
    var toyearfield = toDate.split("-")[2];


    var fromDate = new Date(fromyearfield, frommonthfield-1, fromdayfield);
    var toDate = new Date(toyearfield, tomonthfield-1, todayfield);

    if(fromDate.getTime() > today.getTime()){
        alert("from Date should be less than today")
        return;
    }
    if(toDate.getTime() > today.getTime()){
        alert("to Date should be less than today")
        return;
    }
    if(fromDate.getTime() > toDate.getTime()){
        alert("from date should be less than to date")
        return;
    }
Ramesh Kotha
  • 8,266
  • 17
  • 66
  • 90