Friday, September 17, 2010

How to pass DateTime object from .Net to Flex using json

I have a wcf rest service in .net that needs to serialize an object to json that has a DateTime property and send it back to my flex application.

What I used for doing the serialization to json on .net side is Json.Net from http://james.newtonking.com/projects/json-net.aspx

This is how I did the serialization, I used ISO8601 to format DateTime object, This is the example of ISO8601 format for date : 2011-12-05T08:15:30-05:00

string result = Newtonsoft.Json.JsonConvert.SerializeObject(contentDto, new Newtonsoft.Json.Converters.IsoDateTimeConverter());
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
message = WebOperationContext.Current.CreateTextResponse(result);

Then on Flex side, we make use of DateUtil in as3corelib.swc (you can download this library)


import com.adobe.utils.DateUtil;
var obj:Object = JSON.decode(rawData);
var d:Date = DateUtil.parseW3CDTF(obj.MyDateTime);

then, we can format that Date object to anything you like,

var df:DateFormatter = new DateFormatter();
df.formatString = "YYYY.MM.DD at HH:NN:SS";
df.format(d);

cheers!

1 comments:

Jack said...

Informative post ! I am getting some error while passing datetime object from net. Can you please what I am missing..I checked the serialization. It is looking to be done in right manner..Please help me ..
electronic signature pad

Post a Comment