Search code examples
knockout.jskogrid

How to implement DateTime sorting in the KoGrid


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?


Solution

  • 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;}