12 June 2012

How to parse a ASP.Net JSON formatted date in C#

ASP.Net serializes a date to JSON in a Microsoft specific format:

/Date(1338505200000)/

The value 1338505200000 is the number of milliseconds since January 1st 1970 UTC.

The data can be parsed in C# removing the placeholders "/Date(" and ")/" and parsing it as:

string jsonDate = "/Date(1338505200000)/"; jsonDate = jsonDate .Replace("/Date(", string.Empty); jsonDate = jsonDate.Replace(")/", string.Empty);

var date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(long.Parse(jsonDate));

1 comment:

Athiban Raj said...

This method fine ! but i get the date 1 day less than the actual date ! :(
So, i have to use date.AddDays(1) to compensate the 1 day loss. Is there a better way ?