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?

1
  • For the future: bit.ly/QcITo9 Commented Sep 9, 2012 at 9:18

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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]); 

Comments

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.