Sort by time (format: hh: mm a) in JavaScript for use with DataTables

I am trying to sort data by time in JavaScript.

Reply to How to sort by time (format: 5:40 PM) in javascript for use with DataTables? works for a data set, but if you turn it on more times, for example. 9:30 pm, 8:15 am, sorting breaks and mishandles these times.

I work in the same way, but at least 50 entries at a time.

+3
source share
1 answer

You can use the following sorting 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 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

+2
source

All Articles