Sorting Dates in a Flex Datagrid
So, file this under "I can't believe it took me that long to figure this out" catagory, but I just spent the past 2 hours trying to work through a solution for sorting a date column in a datagrid. By default, the datagrid sorting sorts by alphabetic or numeric order. If a date is in your dataprovider, it probably rendered it in the grid as a string. So, if you have a list of dates, the first ones showing up are probably every date with a Friday as a day. If you resort, all the Wednesdays are on top... GRRRR!
I did some searching and found some pointers on what to do. Most of them pointed to resorting the array (not an array collection) or ordering them on the server prior to getting them in Flex/Flash. The solution is much easier than working through a bunch of code for either of these. In your datagrid, define the columns with <mx:DataGridColumn> tags. In the date column define a 'sortCompareFunction' property to be a function like this:
private function compareDates(d1:Object, d2:Object):int
{
var d1ms:Number = new Date(d1.DATE FIELD NAME).getTime();
var d2ms:Number = new Date(d2.DATE FIELD NAME).getTime();
if(d1ms > d2ms)
{
return -1;
}
else if(d1ms < d2ms)
{
return 1;
}
else
{
return 0;
}
}
Replace your date field name from the dataprovider where indicated. That's it. Two hours for that... Boy, do I miss just working in Photoshop ;)
