views:

54

answers:

1

Hi

I want to sort by

Month Day Year Hour Minute PM/AM (MM/dd/yyyy h mm tt)

I want to change this what does dd/mm/yy

However I am not sure how to do this

jQuery.fn.dataTableExt.oSort['uk_date-asc']  = function(a,b) {
    var ukDatea = a.split('/');
    var ukDateb = b.split('/');

    var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
    var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

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

jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
    var ukDatea = a.split('/');
    var ukDateb = b.split('/');

    var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
    var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

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

http://datatables.net/plug-ins/sorting

Edit

So I got it sorting ascending but I don't know how to write it for descending.

jQuery.fn.dataTableExt.oSort['datetime-asc'] = function (a, b)
{
    var firstDate = new Date(a);
    var secondDate = new Date(b);

    if (firstDate == secondDate)
    {
        return 0;
    }
    else if (firstDate > secondDate)
    {
        return 1;
    }
    else
    {
        return -1;
    }
};

jQuery.fn.dataTableExt.oSort['datetime-desc'] = function (a, b)
{
    var firstDate = new Date(a);
    var secondDate = new Date(b);

    if (secondDate == firstDate)
    {
        return 0;
    }
    else if (secondDate > firstDate)
    {
        return 1;
    }
    else
    {
        return -1;
    }
};
A: 

What the demo code does is basically this:

  1. split the date string.
  2. put the result array together in the order of wanted type of sort. e.g. the result of 23/06/10 will be 100623.
  3. get the integer value of it by applying mathematical operator.
  4. compare them.

The code has serious flaws if user data has some date like 04/06/89 and 23/06/10.

If your date strings are in one of the formats that JavaScript recognizes by default, I'd suggest you construct two Date object first. e.g.

var x = new Date(a);
var y = new Date(b);
if (x.getMonth() > y.getMonth() || x.getDate() > y.getDate()) {
    return 1;
} else if (x.getMonth() < y.getMonth() || x.getDate() < y.getDate()) {
    return -1;
} else {
    return 0;
}

enrich this code by referencing the Date API of JavaScript, you'll get your result.

nil
so is 1 greater, -1 less zero equal?
chobo2
@chobo2 yes, you're right.
nil
ok see my edit.
chobo2