Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery date sorting [duplicate]

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

like image 589
Sandeep Kumar Avatar asked May 17 '12 13:05

Sandeep Kumar


2 Answers

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

like image 197
Parth Thakkar Avatar answered Oct 15 '22 20:10

Parth Thakkar


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.

like image 30
PinnyM Avatar answered Oct 15 '22 20:10

PinnyM