10

Possible Duplicate:
Javascript date sorting by convert the string in to date format

I am not good in jquery so I was wondering if there is a way or plugin I can use to sort date divs. I have date in YYYY:MM:DD HH:MM:SS format. I am displaying date in divs as shown below. Divs are in unordered format and I want to sort them on latest date first basis.

<div id="dateDiv">2012-04-15 10:25:45</div>
<div id="dateDiv">2012-04-10 19:41:08</div>
<div id="dateDiv">2012-04-20 07:00:10</div>
<div id="dateDiv">2012-04-12 16:45:50</div>

Thanks

Community
  • 1
  • 1
Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110
  • Take a look this question -> http://stackoverflow.com/questions/2769301/how-can-i-set-the-mindate-maxdate-for-jqueryui-datepicker-using-a-string Looks similar to yours. – devasia2112 May 17 '12 at 13:41
  • 7
    As a side note, using duplicate `id`s is a big no-no. – Richard Neil Ilagan May 17 '12 at 13:43
  • @RichardNeilIlagan: Sorry my mistake. I haven't used duplicate id in actual code I just did copy paste of same dive here in the exmple for the sake of convinience. – Sandeep Kumar May 17 '12 at 15:55

2 Answers2

18

I don't know much about plugins...although if you want a light weight method without plugins, you may try this:

html:

<div id="D">
    <div class="dateDiv">2012-04-15 10:25:45</div>
    <div class="dateDiv">2012-04-10 19:41:08</div>
    <div class="dateDiv">2012-04-20 07:00:10</div>
    <div class="dateDiv">2012-04-12 16:45:50</div>
</div>

For js:

var elems = $.makeArray($(".dateDiv"));
elems.sort(function(a, b) {
    return new Date( $(a).text() ) < new Date( $(b).text() );
});
$("#D").html(elems);

UPDATE:
Thanks to CMS for answering this question about parsing dates: Why does Date.parse give incorrect results?

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4], parts[5]); //     months are 0-based
}

var elems = $.makeArray($(".dateDiv"));
elems.sort(function(a, b) {
    console.log( parseDate( $(a).text() ) );
    return parseDate( $(a).text() ) < parseDate( $(b).text() );
});
$("#D").html(elems);​

Now, don't tell me this doesn't work...hehe

Community
  • 1
  • 1
Parth Thakkar
  • 5,427
  • 3
  • 25
  • 34
9

You can use the date.js library combined with this sorter function to do this:

$('#dateDiv').sortElements(function(a, b){
    return Date.parse($(a).text()) > Date.parse($(b).text()) ? 1 : -1;
});

The original repo has not been maintained, but an updated fork of it appears to be in progress here.

PinnyM
  • 35,165
  • 3
  • 73
  • 81