How to implement DateTime sorting in the KoGrid

257 Views Asked by At

I have a KoGrid with DateTime row. And I want have ability for sorting this row. I try to implement custom sortFn function for compare DateTimes instead strings. But it doesn't work correctly(3/03/2017 02:20 PM upper than 31/04/2016 02:20 PM)

  sortFn:function (a, b) {
           var a1 = moment(a,"'DD/MM/YYYY hh:mm A").format("YYYY-MM-DD HH:mm");
           var b1 = moment(b,"'DD/MM/YYYY hh:mm A").format("YYYY-MM-DD HH:mm");
                return (a1 > b1);
                }

https://jsfiddle.net/L681pgny/

How I can fix it? And how I can debug sortFn function?

Additional question: Sorting function is working only for current page now. Is it possible sort all items from all pages and show 5(for jsfiddle example above) matching items on the page?

2

There are 2 best solutions below

0
dmoo On BEST ANSWER

The sort function needs to return a 1 or -1 or 0 if they are the same. You are only returning 1 and 0.

sortFn:function (a, b) {
  var a1 = moment(a,"'DD/MM/YYYY hh:mm A");
  var b1 = moment(b,"'DD/MM/YYYY hh:mm A");
  return a1.isBefore(b1) ? 1 : -1;}
0
AldoRomo88 On
  • When you use format you are converting moment to strings, omite that part.
  • Isn't well documented but apparently sortFn need to return 1 or -1 to works properly

This is what your sortFn should contains

var a1 = moment(a,"'DD/MM/YYYY hh:mm A");
var b1 = moment(b,"'DD/MM/YYYY hh:mm A");

return a1>b1?1:-1;
                

Check working fiddle