Sunday, February 28, 2021

Date sorting in Kendo UI Grid for dd.MM.yyyy format

Date sorting not working as expected in Kedno grid when format does not follow the order YEAR -> MONTH -> DAY.

It is because dates are treated as strings objects and they are compared as plain text.

One solution is to parse strings to dates and sorting will work in an expected manner.

KendoGridSortedDate.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var orders = [        
    { OrderDate: '10 20 1999' }, 
    { OrderDate: '2/06/2015' }, 
    { OrderDate: '09/09/2112'}
];

$("#singleSort").kendoGrid({
    dataSource: {
        schema: {
            model: {
                fields: {
                    OrderDate: {
                        type: "date",
                        parse: function (e) {
                            return new Date(e)
                        }
                    }
                }
            }
        },
        data: orders
    },
    sortable: true,

    columns: [
        {
            field: "OrderDate",
            title: "Order Date",
            format: "{0:dd.MM.yyyy}"
        }
    ]
});

KendoGridSortedDate.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
  <head>
   
    <style>html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }</style>
    <title></title>
   
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.default.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.default.min.css" />

    <script src="http://cdn.kendostatic.com/2015.1.318/js/jquery.min.js"></script>
    <script src="http://cdn.kendostatic.com/2015.1.318/js/angular.min.js"></script>
    <script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>

  </head>
  <body>
    <div class="demo-section k-header">
      <div id="singleSort"></div>
    </div>

    <script src="KendoGridSortedDate.js"></script>

  </body>
</html>

Source links:

Sorted grid


No comments: