3

I'm attempting to sort data by time in JavaScript.

The answer at How do I sort by time (format: 5:40 PM) in javascript for use with DataTables? works for the data set but if you include more times, eg. 9:30 PM, 8:15 AM, the sort breaks down and mishandles these times.

I'm working on the same sort but with no less than 50 records at a time.

Community
  • 1
  • 1
Alberto Lopez
  • 247
  • 4
  • 10
  • Im referencing the answer here.. http://stackoverflow.com/questions/8752172/how-do-i-sort-by-time-format-540-pm-in-javascript-for-use-with-datatables – Alberto Lopez May 02 '12 at 14:38

1 Answers1

2

You can use the following sort functions :

jQuery.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {

  x = getTimeValue(x);
  y = getTimeValue(y);

  return x<y?-1:x>y?1:0;

};

jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {

  x = getTimeValue(x);
  y = getTimeValue(y);

    return x<y?1:x>y?-1:0;
};

and the getTimeValue() method :

function getTimeValue(x) {
  var time = x.match(/(\d+)(?::(\d\d))?\s*(P?)/);
  var h = parseInt(time[1],10) + (time[3] ? 12 : 0);
  if(!time[3] && parseInt(time[1],10)==12) h = 0;
  if(time[3] && parseInt(time[1],10)==12) h = 12;
  return h * 60 + ( parseInt(time[2],10) || 0 );
}

Working example here

Manse
  • 37,765
  • 10
  • 83
  • 108
  • Although not _nearly_ as clear, note that you can write the return value with far less typing, as simply this: `return x<1?-1:x>1?1:0;` This is only acceptable, IMHO, because you always see it at the end of a custom comparator. – Phrogz May 02 '12 at 15:27
  • @Phrogz are you sure ? [doesnt work here](http://live.datatables.net/erefom/17/edit). There is no comparison to `y` in your statement ? – Manse May 02 '12 at 15:30
  • Bah! Typos; I meant `return xy?1:0`; simply that the precedence is 'correct' such that parentheses are not needed. (Apparently having "one" and "why" starting with the same sound in my head was enough to fool the failing homonymic transcription devices that I call "fingers".) – Phrogz May 02 '12 at 15:35
  • @Phrogz still a no-go ... sorting is one way ... http://live.datatables.net/erefom/18/edit – Manse May 02 '12 at 15:37
  • There is still something going on in my DataTable that is throwing the sort off. It appears that 08:00 and 9:00 o clock hours are getting assigned 0 for the hours in the AM and 12 in the PM and being mixed in with those hours for some reason. I am using exactly the javascript from the example. Could this have something to do with parsing? – Alberto Lopez May 02 '12 at 15:53
  • Oh, absolutely. Naughty Manse! `parseInt('08')` is `0`, because of octal! You can fix by using `parseInt(str,10)`, or better by just using `str*1`. I have changed my upvote to a downvote until the [evil usage of parseInt](http://stackoverflow.com/a/10184402/405017) is fixed. – Phrogz May 02 '12 at 15:59