Date Sort in a DataGrid – the easy way

While trying to give suggestions to a post on the Flex Forum, I modified my Simple Data Grid to include a column for a Date. The poster had an issue with sorting the column with dates in it. My guess is, the Date value is actually a String object. It really isn’t very hard to create a Date from a string, just parse out the String and feed the appropriate date times into the Date object. Here is how I create the random date value.

// Create a Random Date
var randomMonth:Number = Math.floor(Math.random() * (11));
var randomDay:Number = Math.floor(Math.random() * (27));
var randomHour:Number = Math.floor(Math.random() * (23));
var randomMinute:Number = Math.floor(Math.random() * (59));
var thisDate:Date = new Date();
thisDate.month = randomMonth; = randomDay;
thisDate.hours = randomHour;
thisDate.minutes = randomMinute;

Since I insert the value into the item Object as a Date object, the sort function knows how to sort for Descending/Ascending. It might take a few more steps to convert a set of String data into objects and insert them into an ArrayCollection, but I think it saves time in the long run, because you work with each value as what they are and not a String that you have to convert to a Number, Int or Date.

Here is the DataGrid example. Not only does sorting by the column header work for the dates, I added a button to sort by the dates. The button switches between Ascending and Descending each time it is clicked.
View Source

Leave a Reply