0

There are lots of examples of how to parse a "json date" in C# using .net4+, But I havent found many which will work on .Net 2.0.

Like this one Parsing JSON DateTime from Newtonsoft's JSON Serializer which works great if you have .net4 and can use libraries..

I however only have base .Net 2 at my disposal.

So, what is the best way to parse this:

"/Date(1427565325073+0100)/"

To a C# System.DateTime.

My code current code does not work with timezones.

private System.DateTime ParseJsonDate(string jsondate)
{
    jsondate = jsondate.Replace("/Date(", "");
    jsondate = jsondate.Replace(")/", string.Empty);  
    var expDate = new System.DateTime(long.Parse(jsondate));

    return expDate;
}
Community
  • 1
  • 1
JensB
  • 6,663
  • 2
  • 55
  • 94
  • Try this URL: http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx – Niels Mar 29 '15 at 19:06

1 Answers1

1

First of all, you can try to find early versions of JSON.NET, I believe there are some that support .NET 2.0.

If you can't find any, you can to through JSON.NET source code on github and find the code, which does the job and proved by the time and people.

Or you can write your own implementation based on my small sample:

var input = "/Date(1427565325073+0100)/";

var dateVal = input.Substring(6, input.Length - 8);
Console.WriteLine(dateVal);

var parts = dateVal.Split('+');
var milliseconds = long.Parse(parts[0]);
var utcTime = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds);
Console.WriteLine(utcTime);

var localTime = utcTime;
if (parts.Length > 1)
{
    var hoursMinutes = int.Parse(parts[1]);
    localTime = localTime.AddHours(hoursMinutes / 100).AddMinutes(hoursMinutes % 100);
}
Console.WriteLine(localTime);
ie.
  • 5,982
  • 1
  • 29
  • 44
  • According to the [documentation](http://www.newtonsoft.com/json/help/html/Introduction.htm), Json.NET "Supports .NET 2, .NET 3.5, .NET 4, .NET 4.5, Silverlight, Windows Phone and Windows 8 Store". So OP should be able to use the current version. – dbc Mar 29 '15 at 19:39
  • @dbc great! so the problem should go away – ie. Mar 29 '15 at 19:40