Search Flex Components Free

Custom Search

December 7, 2007

Storing Dates as Strings in Flex while using Date Components and Date Sorting


Due to an existing implementation of the application I'm working on and problems transferring Dates from Fluorine (.NET Remoting Gateway) to Flex, I decided to store and pass all my Dates as Strings. At first, this seemed like a reasonable and easy to implement change. As time has gone on, more and more problems seem to arise. I'm sure the best thing to do would be to find a way to use Date-typed Dates, but I've figured out and thought I'd share some workarounds/hacks in case anyone else is trying to/forced to use Strings as Dates.
1) Binding my dates to a DataGrid column:In order to have my dates display in the form mm/dd/yyyy, I do the following:Call a labelFunction named "dateLabel" which then calls a static function from my Util package "formatDateDisplay"
PLAIN TEXT
XML:

PLAIN TEXT
Actionscript:
private function dateLabel(item:Object, column:DataGridColumn):String
{
return Utils.formatDateDisplay(item[column.dataField]);
}
PLAIN TEXT
Actionscript:
//This is found in my Utils Package
public static function formatDateDisplay(date:String):String
{
// This removes any time data that is appened onto my Date String
return date.substr(0, date.search(' '));
}
2) My DataGrid Columns should be able to be sorted by Date rather than by String ComparisonCall a sortCompareFunction named "dateMyDatePropertyCompare" which then calls a static function from my Utils package "dateFromStringSortCompare"
PLAIN TEXT
XML:

PLAIN TEXT
Actionscript:
private function dateMyDatePropertyCompare(obj1:Object, obj2:Object):int
{
return Utils.dateFromStringSortCompare(obj1.myDateProperty, obj2.myDateProperty);
}
PLAIN TEXT
Actionscript:
public static function dateFromStringSortCompare(obj1:String, obj2:String):int
{
var date1:Date = (obj1 == '' obj1 == null) ? null : new Date(obj1);
var date2:Date = (obj2 == '' obj2 == null) ? null : new Date(obj2);

if (date1 return -1;
else if (date1> date2)
return 1;
else
return 0;
}
3) Binding my String-Date to a DateFieldYou can not bind a String to a DateField selectedDate property, so it must be cast into a Date Type. The only way I've found to make this Bind is to do the following:
PLAIN TEXT
XML:
selectedDate="{(model.myDateProperty == null model.myDateProperty == '') ? null : new Date(model.myDateProperty)}"
and to save the DateField value to a String:
PLAIN TEXT
Actionscript:
obj.myDateProperty= myDateField.selectedDate.toDateString();
My hope is that one of the following happens from this post:
- Someone can save some time and use something I've written here- I'll learn a much cleaner way to do this and I'll follow this up with a "I can't believe i was doing that, now I'm doing this...post"
Comments are welcome and hoped for as always....

Related Flex Tutorials