Search code examples
c#jsondatetimejson-deserialization

C# : Could not parse the correct date and time to the current system time zone


I have a service which returns a json like this :

[  
   {  
      "title":"First event",
      "startDate":"\/Date(1495512000000-0400)\/",
      "endDate":"\/Date(1495857540000-0400)\/",
   }
]

I deserialize the json output to the list with respect to the model I have defined :

Model

public class EventModel
{
    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("startDate")]
    public DateTime StartDate { get; set; }

    [JsonProperty("endDate")]
    public DateTime EndDate { get; set; }
}

C# Code of deserialization

I am using Newtonsoft.Json package for deserialization.

List< EventModel > lstEvent = new List< EventModel >();
lstEvent = JsonConvert.DeserializeObject<List< EventModel >>(await objMyServices.GetData());

So in this case when I debug I get the following output in two different timezone:

For GMT+5:30 (Kolkata - India):

Start Time : 23-05-2017 09:30:00

End Time : 27-05-2017 09:29:00

For GMT-4:00 (New York):

Start Time : 23-05-2017 00:00:00

End Time : 26-05-2017 23:59:00

Therefore for every record, start time is not parsed to the respective system time zone when I switch to GMT-4:00 (New York). What is the thing I am missing here ?


Solution

  • Json.NET allows you to specify what kind of DateTime to return (UTC, Local) through the DateTimeZoneHandling serializer setting. The default is Local.

    To return a UTC DateTime, use DateTimeZoneHandling.Utc :

    var settings = new Newtonsoft.Json.JsonSerializerSettings() 
                   {
                       DateTimeZoneHandling = DateTimeZoneHandling.Utc 
                   };
    var content=await objMyServices.GetData();
    var lstEvent = JsonConvert.DeserializeObject<List<EventModel>>(content, settings);
    

    Perhaps a better option is to change the property types to DateTimeOffset. This type preserves the original offset.