ricardo.poblete

Adobe Flex, ActionScript 3, etc…

How to sort dates correctly with a datagrid column

Posted by ripoblet on June 11, 2008

When we have datagrid column showing is a date field, but when retrive from database sometimes formated “DD/MM/YYYY HH24:mi” (oracle format), the datagrid column can’t sort correct because it’s trying to sort strings alphabetically and strings dates are not words, are dates. (obviously).

Example Preconditions: Objects in dataprovider have a “DATE” property with a string date, example “11/06/2008 17:45″

 

This time the solution is

1) Transform strings format dates to date format dates

2) Create sort function

3) Set datagrid colum with the property “sortCompareFunction”

 Code

1) Transform function called String2Date

 private function String2Date(date:String):Date{

var day_month:Array = date.split(‘/’); //cut day, month and year with hour 

      var day:int = new Number(day_month[0]);

      var month:int = new Number(day_month[1]);

      var year_hour:String = day_month[2];

     

      var arr:Array = year_hour.split(‘ ‘); //cut year and hours with minutes separated by a space ” “

      var year:int = new Number(arr[0]);

      var hour_minutes:String = arr[1];

                   

      var arr2:Array = hour_minutes.split(‘:’); // cut hour and minutes seperated by “:”

      var hour:int = new Number(arr2[0]);

      var minutes:int = new Number(arr2[1]);

                 

      var date_date:Date = new Date(year, month -1, day, year, minutes, 0, 0);

             

      return date_date;

}

 

2) Compare function called “sortDates”

 

public function sortDates(itemA:Object, itemB:Object):int {

var dateA:Date = String2Date(itemA.FECHA);

      var dateB:Date = String2Date(itemB.FECHA);

      return ObjectUtil.dateCompare(dateA, dateB);

}

3) Finally set datagrid column, o suppose you have a defined column datagrid

 

<mx:DataGridColumn headerText=”Date” dataField=”DATE” sortCompareFunction=”sortDates/>

 

Now you can sort dates in a datagrid.

 

PD: If you have a simple date string format like “DD/MMM/YYYY” modify String2Date function.

END

 

Regards

 

ripoblet

 

One Response to “How to sort dates correctly with a datagrid column”

  1. andhapp said

    If you are using flex 2…can you not just use sortable = true inside your DataGridColumn tag and as far as the date formatting is considered use the dateFormatter like this:

    1) Define a private function
    private function dateLabel(item:Object, column: DataGridColumn) : String {
    return dateFormatter.format(item[column.dataField]);
    }

    2) In the DataGridColumn just add labelFunction=”dateLabel”

    This gives you freedome to choose the format you like…

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>