Wednesday, September 12, 2012

Dealing with JSON format date

When working with web application and dealing with JSON formatted data, we may come across date types that are represented as /Date(1347490800000)/. The value between the parenthesis i.e. 1347490800000 indicates the number of milliseconds elapsed since 1st Jan 1970.

In order to show the date in human understandable format, we will have to construct the date object using these millisecond values. In JavaScript, this can be done as follows:

var myJSONDate = "/Date(1347490800000)/"; //For demonstration purpose but in realtime we will get from Ajax call returning data in JSON format
var value = new Date(parseInt(myJSONDate.replace(/\/Date\((.*?)\)\//gi, "$1")));

In the above method, we have used native JavaScript’s regular expression technique to get hold of the millisecond value stripping the /, Date and parenthesis characters. In JavaScript, the new date object by default starts from 1st Jan 1970.

Similarly, we will can construct the DateTime object in .NET from JSON date as follows:

var jsonDate = "/Date(1347490800000)/";
jsonDate = System.Text.RegularExpressions.Regex.Replace(jsonDate, @"/Date\((.*?)\)\/", "$1");
var date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(long.Parse(jsonDate));

Hope this helps…

No comments: