jqGrid not sorting properly on Date object
Asked Answered
O

1

3

We are using jqGrid in local mode and as part of our ajax call the Json result is being modified so that dates are converted into valid JS Date objects. The problem is that these aren't sorting properly.

My colModel is below:

       {
            name: 'reservationTime',
            index: 'reservationTime',
            sorttype: 'date'
        }

For the most part they are in "order" but the first is from the middle of the data and half way through is a record from near the beginning.

When I click the header to try to sort it asc/desc it doesn't change at all. If I sort another field that works fine and when I then sort by my date field it will do the broken sort again but that's it.

Ouabain answered 15/3, 2012 at 19:48 Comment(1)
I posted the pool request which will fix the problem (see my UPDATED answer).Barnaba
B
3

jqGrid don't support the Date as native datatype in compare operations so I suggest you two ways as the workaround.

1) You can use sorttype as function. In the case the function will be called with Date parameter and the function can return the string which can be used instead of Date in compare operations. For example

sorttype: function (d) {
    if ($.isFunction(d.toISOString)) {
        return d.toISOString();
    }

    return ISODateString(d);
    // see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
    function ISODateString(d) {
        function pad(n) { return n < 10 ? '0' + n : n; }

        return d.getUTCFullYear() + '-'
            + pad(d.getUTCMonth() + 1) + '-'
            + pad(d.getUTCDate()) + 'T'
            + pad(d.getUTCHours()) + ':'
            + pad(d.getUTCMinutes()) + ':'
            + pad(d.getUTCSeconds()) + 'Z'
    }
}

2) You can extend the _compare function used internally by jqGrid to support Date type. You can use the trick which I described in my this old answer. In case of usage of _compare the code will be

var oldFrom = $.jgrid.from;

$.jgrid.from = function (source, initalQuery) {
    var result = oldFrom.call(this, source, initalQuery),
        old_compare = result._compare;
    result._compare = function (a, b, d) {
        if (typeof a === "object" && typeof b === "object" &&
                a instanceof Date && b instanceof Date) {
            if (a < b) { return -d; }
            if (a > b) { return d; }
            return 0;
        }
        return _compare.call(this, a, b, d);
    };
    return result;
};

You can insert the code before the usage of jqGrid like I demonstrate it on the demo.

UPDATED: I posted the pull request which fix the problem.

Barnaba answered 15/3, 2012 at 20:59 Comment(1)
@ShaneCourtrille: the pull request is already merged (see here) with the main code of jqGrid. So the next version of jqGrid will sort correctly with local data having Date type.Barnaba

© 2022 - 2024 — McMap. All rights reserved.