I’ve been developing a Sencha Touch Mobile app recently, that interface with a WCF REST service exposing data via JSON. One of the issues I faced was parsing the dates returned from the service into a date type in the Sencha Touch Data Model. This post explains one way to do that.
Say we have a simple model that only holds an id and a date:
1 | Ext.regModel( "MyModel" , { |
4 | {name : 'MyDate' , type : 'date' }, |
When data is read into this model using a Proxy from a WCF REST JSON service, the MyDate column will just hold the string representation of the data such as “/Date(1238606590509+0800)/”, ie. it won’t be parsed. The trick to overcome this is to utilize the “convert” property that you can set on a field. This allows you to call out to a helper function every time a value will be set on the model for that field.
Now our model looks like this:
1 | Ext.regModel( "MyModel" , { |
4 | {name : 'MyDate' , type : 'date' , convert : toDateFromJSON}, |
We need to define our converter function;
1 | function toDateFromJSON(v, record) { |
2 | return Date.parseDate(v, "M$" ); |
In this converter function we utilize the built in Date object. When giving it the format string “M$” it will parse Microsoft Serialized AJAX dates which is what’s used with WCF, REST and the JSON formatter OOB.
Now our model will have the correct datatype for the MyDate property, which will allow us to call useful functions on it such as format.