Sorting date columns in a DataGrid

by Peter deHaan on August 12, 2007

in DataGrid, ObjectUtil

Here’s an example of sorting a column of dates in a Flex DataGrid. The dates start out as Strings (such as “04/14/1980″) so you create a custom sortCompareFunction on that DataGrid column which converts the strings to dates so Flex will sort the dates in sequential order (as oppsed to string order). Hope that helps somebody out there.

I also created a little tooltip on the date column which shows the dates in a somewhat more readable form (”April 14 1980″) using the DataGridColumn object’s showDataTips and dataTipFunction properties.

Full code after the jump.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/12/sorting-date-columns-in-a-datagrid/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.utils.ObjectUtil;

            private function date_sortCompareFunc(itemA:Object, itemB:Object):int {
                /* Date.parse() returns an int, but
                   ObjectUtil.dateCompare() expects two
                   Date objects, so convert String to
                   int to Date. */
                var dateA:Date = new Date(Date.parse(itemA.dob));
                var dateB:Date = new Date(Date.parse(itemB.dob));
                return ObjectUtil.dateCompare(dateA, dateB);
            }

            private function date_dataTipFunc(item:Object):String {
                return dateFormatter.format(item.dob);
            }
        ]]>
    </mx:Script>

    <mx:ArrayCollection id="arrColl">
        <mx:source>
            <mx:Array>
                <mx:Object name="User A" dob="04/14/1980" />
                <mx:Object name="User B" dob="01/02/1975" />
                <mx:Object name="User C" dob="12/30/1977" />
                <mx:Object name="User D" dob="10/27/1968" />
            </mx:Array>
        </mx:source>
    </mx:ArrayCollection>

    <mx:DateFormatter id="dateFormatter" formatString="MMMM D, YYYY" />

    <mx:DataGrid id="dataGrid" dataProvider="{arrColl}">
        <mx:columns>
            <mx:DataGridColumn dataField="name"
                    headerText="Name:" />

            <mx:DataGridColumn dataField="dob"
                    headerText="Date of birth:"
                    sortCompareFunction="date_sortCompareFunc"
                    showDataTips="true"
                    dataTipFunction="date_dataTipFunc" />
        </mx:columns>
    </mx:DataGrid>

</mx:Application>

Stored as a note on how to create a custom compare function in Flex