Friday, July 3, 2009

JSON Flex Dates

If your Flex datagrid dates look like this:



And you want them to look like this:




You will want to call the fixDates function before passing your data string to the JSON.decode function.



//get the raw JSON data and cast to String
var rawData:String = String(event.result);

//fix the dates
rawData = fixDates(rawData);

//decode the data to ActionScript using the JSON API
var arr:Array = (JSON.decode(rawData) as Array);


// fix any dates of the format "\/Date(1280718000000-0300)\/"
// to a format like this Mon Aug 2 2010 12:00:00 AM
private function fixDates(data:String):String
{
var temp:String = data; //copy incoming data to temporary string
var pattern:RegExp = /\\\/Date\(\d*\-\d*\)\\\//gi; //create regular expression to search for dates
var dates:Array = temp.match(pattern); //array of all dates found

for (var i:int=0; i< dates.length; i++){ //iterate through array of dates
var milliseconds_and_offset:RegExp=/\d*\-\d*/gi; //create regular expresion to search for millisecond
//and offset values Ex. 1246624494320-0300
var values:Array = dates[i].toString().match(milliseconds_and_offset);

var time:Array = values[0].toString().split("-"); //separate the millisecond and offset values
var milli:Number = new Number(time[0].toString()); //store milliseconds
var offset:Number = new Number (time[1].toString());//store offset

var replacementDate:Date = new Date(); //create a new replacement date
replacementDate.setTime(milli); //set new date with the correct time

//search and replace
data =this.searchAndReplace(data,dates[i].toString(),replacementDate.toLocaleString());
}
return data;
}



private function searchAndReplace(holder:String, searchfor:String, replacement:String):String
{
var temparray:Array = holder.split(searchfor);
holder = temparray.join(replacement);
return holder;
}

No comments:

Post a Comment