steve steve - 2 months ago 5
Javascript Question

convert date string to yyyy-mm-dd pragmatically

I have written a very small, lightweight custom function that orders a table based on it's value. This function works on all columns and scales nicely.

The problem I have is when it comes to ordering by date. The data retrieved from the database (which cannot not be changed) is in the format dd-mm-yyyy. Obviously this is ordering by the first value, which will not give the desired result as

01-06-2016
should not become before
09-01-2016
.

I could write a seperate function that does various date conversions and comparisons but my attemps thus far have become very bloated. Almost becoming larger than the oringinal function. Could someone please suggest a clean way of doing this?

DEMO http://jsfiddle.net/6sskjbod/565/

function sortTable(order, col) {
var rows = $('#mytable tbody tr').get();

rows.sort(function(a, b) {

var A = $(a).children('td').eq(col).text().toUpperCase();
var B = $(b).children('td').eq(col).text().toUpperCase();

if (order) {
if (B < A) return -1;
if (B > A) return 1;
} else {
if (A < B) return -1;
if (A > B) return 1;
}

return 0;
});

$.each(rows, function(index, row) {
$('#mytable').children('tbody').append(row);
});
}

Answer

You could ad a 'date' class to specific th and then deal with them differently within the function themselves. In this example i simply detec if it's a date value by checking the class and then reverse the values so it reads yyyy-mm-dd

https://jsfiddle.net/kplcode/2nvopbqo/1/

$(".sort").click(function() {
  var col = $(this).parent().children().index($(this));
  var desc = $(this).hasClass('desc');
  var date = $(this).hasClass('date');
  sortTable(desc, col, date);
  $(this).toggleClass("desc asc");
});

function sortTable(order, col, date) {
  var rows = $('#mytable tbody  tr').get();

  rows.sort(function(a, b) {

    var A = $(a).children('td').eq(col).text().toUpperCase();
    var B = $(b).children('td').eq(col).text().toUpperCase();

    if(date) {
      var A = A.split("-").reverse().join('-');
        var B = B.split("-").reverse().join('-');
    }

    if (order) {
      if (B < A) return -1;
      if (B > A) return 1;
    } else {
      if (A < B) return -1;
      if (A > B) return 1;
    }

    return 0;
  });

  $.each(rows, function(index, row) {
    $('#mytable').children('tbody').append(row);
  });
}
Comments