jqGrid not sorting properly on Date object

有些话、适合烂在心里 提交于 2020-01-24 10:36:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9727075/jqgrid-not-sorting-properly-on-date-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!