0

In an attempt to create a list sortable by date, I created the following datasource:

sort: { field: 'dateTime', dir: 'asc' },
schema: {
    model: {
        id: 'Id',
        fields: {
            dateTime: {
                field: 'DateTime',
                type: 'Date',
                parse: function (value) {
                    return kendo.toString(kendo.parseDate(value), 'MM/dd/yyyy hh:mm tt');
                }
            },
            stuff: 'Stuff'
        }
    }
}

After filling it with data, I noticed that the rows in the bound list were sorting alphabetically like:

  • 01/02/2015 08:22 PM
  • 12/12/2014 09:00 PM
  • 12/18/2014 08:22 PM

How can I get these dates to sort in ascending chronological order?

CuddleBunny
  • 1,941
  • 2
  • 23
  • 45

1 Answers1

1

I imagine this occurred because the value was converted to a string in the parse function so it was no longer sorting like a date so I removed the parsing code from the field:

sort: { field: 'dateTime', dir: 'asc' },
schema: {
    model: {
        id: 'Id',
        fields: {
            dateTime: {
                field: 'DateTime',
                type: 'Date'
            },
            stuff: 'Stuff'
        }
    }
}

This reverted the dates shown in the listview to the default format: (Fri Dec 12 2014 21:00:00 GMT-0500 (Eastern Standard Time)), but it now sorted correctly. The final piece of the puzzle is to instead bind my element to a calculated property that parses the date instead of the dateTime field like so:

HTML

<!-- The element: -->
<td data-bind="html: myDate" style="width: auto;"></td>

JavaScript

// And in the observable:
myDate: function(e) {
    return kendo.toString(kendo.parseDate(e.dateTime), 'MM/dd/yyyy hh:mm tt');
}

This worked like a charm and I got this:

  • 12/12/2014 09:00 PM
  • 12/18/2014 08:22 PM
  • 01/02/2015 08:22 PM

Optionally, if you have a DateTimePicker bound to your dateTime property your myDate calculated property will not update when you change it. I solved this by listening for the change and triggering the change event manually:

viewModel.bind('change', function (e) {
    if (e.field == 'selectedEvent.dateTime') // or whatever your property comes out as
        viewModel.trigger('change', { field: 'myDate' });
});
CuddleBunny
  • 1,941
  • 2
  • 23
  • 45