rss
twitter

Friday, January 23, 2009

Date sorting in Flex Datagrid


In Flex Datagrid sorting is good for the Strings and Numbers,but when its come for the Date objects its not so, Flex also treats the Date objects as Strings and doing the sorting accordingly.
To sort this according to date you can use custom sortCompareFunction on that datagrid coloumn which converts the strings to dates ,This will make the date sorting to that coloumn



Mxml code :

mx:datagridcolumn datafield="stdate" headertext="Date" showdatatips="true" sortCompareFunction="dateSortCompare" />

Actionscript code :

var marketdata:ArrayCollection=new ArrayCollection([{stdate:"2009-01-03",name:"Q1"},
{stdate:"2009-01-22",name:"Q2"},
{stdate:"2008-11-13",name:"Q3"},
{stdate:"2009-01-21",name:"Q4"},
{stdate:"2008-12-08",name:"Q5"},
{stdate:"2008-01-03",name:"Q5"}]);
private function dateSortCompare( dt1:Object, dt2:Object) : int
{
var t1:Array = dt1["stdate"].toString().split("-");
var t2:Array = dt2["stdate"].toString().split("-");
var t1dt:Number=(new Date(Number(t1[0]),Number(t1[1]),Number(t1[2]))).getTime();
var t2dt:Number=(new Date(Number(t2[0]),Number(t2[1]),Number(t2[2]))).getTime();
if( t1dt <>
else if( t1dt > t2dt ) return 1;
else return 0;
}


This dateSortCompare function get Date objects and extracts the time values from those and compares them. In this situation you may need to use a cellRenderer to format the value in the data grid if your field value format is different from 'YYYY-MM-DD'

Note : Don't use a labelFunction because the sort mechanism will call the labelFunction to pass the values to the sortCompareFunction!

Bookmark and Share

2 comments:

Anonymous,  December 8, 2009 at 7:53 AM  

You have something wrong with:

if( t1dt <>
else if( t1dt > t2dt ) return 1;
else return 0;
}

Gnanz June 1, 2010 at 1:01 AM  

yeah thanks for notifying.
My html tag got eated by blogger :(

Post a Comment

Tech World

Label Cloud

Must Buy

  © Blogger templates by Ourblogtemplates.com updated with zenplate.com tips

Back to TOP