JqGrid not sorting correctly by Date object

We use jqGrid in local mode and as part of our ajax call, the Json result changes so that the dates are converted to valid Date JS objects. The problem is that they are not sorted 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 halfway through is a record from the beginning.

When I click on the title to try to sort it, he / she does not change at all. If I sort another field that works fine, and when I then sort by date field, it will make a broken sort again, but what is it.

+3
source share
1 answer

jqGrid does not support Date as a native data type in comparison operations, so I offer you two paths as a workaround.

1) You can use the sorttype function as a function. In the case when the function will be called with the Date parameter, and the function can return a string that can be used instead of the date in comparison operations. for instance

 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 inside jqGrid to support the Date type. You can use the trick I described in my old answer . If using _compare 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 paste the code before using jqGrid, as shown in the demo .

UPDATED : I sent a transfer request that fixed the problem.

+3
source

Source: https://habr.com/ru/post/911129/


All Articles