0

I have the following snippet for li tag:

tl = '<li>';
    tl+= '<time class="cbp_tmtime" datetime="2013-04-10 18:30"><span>04/10/13</span> <span>18:30</span></time>';
    tl+= '<div class="cbp_tmlabel">';
    tl+= '<p>TL Content Goes here</p>';
    tl+= '</div>';
    tl+= '</li>';

As you can see there's a time tag. Is it possible to use jQuery to sort <ul> based w.r.t datetime attribute?

Volatil3
  • 14,253
  • 38
  • 134
  • 263

2 Answers2

1

Sure it is.

You can write a sort for them: How to define custom sort function in javascript?

Here is a fiddle: http://jsfiddle.net/58eyg7ds/1/ and the code used to create a custom sort for jQuery:

$.fn.sortMyData = function() {
  var elements = $(this).find('> *');

  // Create an array for the content
  var arr = [];

  for (var i = 0; i < elements.length; i++) {
    arr.push(elements.eq(i));
  }

  arr.sort(function(a, b) {
      var dateA = new Date(a.attr('datetime').replace(/([0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}) /, '$1T'))
    var dateB = new Date(b.attr('datetime').replace(/([0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}) /, '$1T'))

    if (dateA < dateB) {
      return -1;
    }

    if (dateA > dateB) {
      return 1;
    }

    return 0;
  });

  for (i = 0; i < arr.length; i++) {
    $(this).append(arr[i]);
  }
}

$('ul').sortMyData();
Community
  • 1
  • 1
adrenalin
  • 1,656
  • 1
  • 15
  • 25
0

Adapting the code from this question, you should be able to do something like this.

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) {
    // Ascending order
    return parseDate( $(a).attr("datetime") ) > parseDate( $(b).attr("datetime") );
});
$("#D").html(elems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="D">
    <div class="dateDiv" datetime="2012-04-15 10:25:45">2012-04-15 10:25:45</div>
    <div class="dateDiv" datetime="2012-04-10 19:41:08">2012-04-10 19:41:08</div>
    <div class="dateDiv" datetime="2012-04-20 07:00:10">2012-04-20 07:00:10</div>
    <div class="dateDiv" datetime="2012-04-12 16:45:50">2012-04-12 16:45:50</div>
</div>
Community
  • 1
  • 1
user4176466
  • 180
  • 6
  • Interesting. However you can pass entire date `2013-04-10 18:30` in `Date()` constructor and it will split it anyway – Volatil3 Oct 24 '14 at 06:40
  • @Volatil3 but passing that to the constructor will lead into an undefined date on Safari and Internet Explorer - Chrome accepts it though. It must include the T to separate time from the date. – adrenalin Oct 24 '14 at 06:46
  • This answer also doesn't use the jQuery wrapper to DOM and doesn't provide a full answer. – adrenalin Oct 24 '14 at 06:51