6

How would I compare the following two dates?

var start_date = $('#start_date').text();
var end_date = $('#end_date').text();
alert(start_date + ' ' + end_date); // '2013-01-01 2013-01-02'

# how to do the following?
if (start_date > end_date) {...}
David542
  • 104,438
  • 178
  • 489
  • 842
  • convert those strings to native JS `Date` objects. right now they're strings, and will be compared using string rules. – Marc B Oct 22 '13 at 17:31
  • possible duplicate of [Compare dates with JavaScript](http://stackoverflow.com/questions/492994/compare-dates-with-javascript) – Jorge Oct 22 '13 at 17:31
  • If you know they are always year-month-day then string comparison is fine. – James Montagne Oct 22 '13 at 17:32
  • possible duplicate of [how to compare two string dates in javascript?](http://stackoverflow.com/questions/14781153/how-to-compare-two-string-dates-in-javascript) – epascarello Oct 22 '13 at 17:33

3 Answers3

20

If this is always in this format (yyyy-mm-dd/2013-01-01) then you can compare as string

var d1 = '2013-11-01', d2 = '2013-11-02';
console.log(d1 < d2); // true
//console.log(d1.getFullYear()); won't work, not date object

See Lexicographical order

An important exploitation of lexicographical ordering is expressed in the ISO 8601 date formatting scheme, which expresses a date as YYYY-MM-DD. This date ordering lends itself to straightforward computerized sorting of dates such that the sorting algorithm does not need to treat the numeric parts of the date string any differently from a string of non-numeric characters, and the dates will be sorted into chronological order. Note, however, that for this to work, there must always be four digits for the year, two for the month, and two for the day

But, you can use this to compare dates

var d1 = new Date("11-01-2013");
var d2 = new Date("11-04-2013");
console.log(d1);
console.log(d1.getMonth()); // 10 (0-11)
console.log(d1.getFullYear()); // 2013
console.log(d1.getDate()); // 1
console.log(d1 < d2); // true

Check this fiddle.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
1

You may try like this:

var d1 = Date.parse("2013-11-01");
var d2 = Date.parse("2013-11-04");
if (d1 < d2)

Also check out Date.parse and Compare dates with JavaScript

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

Try using a timestamp.

var date1 = +new Date("2013-11-01");
var date2 = +new Date("2013-11-04");

console.log(date1);
console.log(date2);

console.log(date1>date2);
Arnaldo Capo
  • 178
  • 1
  • 10