How to preserve timezone when deserializing DateTime using JSON.NET? [duplicate]

心已入冬 提交于 2019-12-09 02:41:58

问题


I'm parsing some JSON in C# using JSON.NET. One of the fields in the JSON is a date/time, like this:

{
    "theTime":"2014-11-20T07:15:11-0500",
    // ... a lot more fields ...
}

Note that the time part is 07:15:11 (TZ of GMT-5 hrs)

I parse the JSON from a stream like this:

 using (var streamReader = new StreamReader(rcvdStream))
 {
     JsonTextReader reader = new JsonTextReader(streamReader);
     JsonSerializer serializer = new JsonSerializer();
     JObject data = serializer.Deserialize<JObject>(reader);
     //...
  }

Then access the time:

DateTime theTime = (DateTime)data["theTime"];

However, this gives me this DateTime object:

{20/11/2014 12:15:11}
Date: {20/11/2014 00:00:00}
Day: 20
DayOfWeek: Thursday
DayOfYear: 324
Hour: 12
Kind: Local
Millisecond: 0
Minute: 15
Month: 11
Second: 11
Ticks: 635520825110000000
TimeOfDay: {12:15:11}
Year: 2014

I need to know the original local time and tz offset, but I seem to have lost that information in the deserialization process, and it is giving me the time in what I presume is my local time (I'm in the UK, so currently at GMT+0).

Is there a way for me to preserve the timezone information when deserializing?

EDIT: added more detail about how I'm deserializing.


回答1:


I would use DateTimeOffset for this instead. DateTime doesn't have any useful time zone information associated with it.

You can deserialize to DateTimeOffset instead by changing serializer.DateParseHandling:

JsonSerializer serializer = new JsonSerializer();
serializer.DateParseHandling = DateParseHandling.DateTimeOffset;

JObject data = serializer.Deserialize<JObject>(reader);

var offset = (DateTimeOffset)data["theTime"];

Console.WriteLine(offset.Offset);    // -5:00:00
Console.WriteLine(offset.DateTime);  // 11/20/2014 7:15:11 AM

Example: https://dotnetfiddle.net/I9UAuC



来源:https://stackoverflow.com/questions/27043220/how-to-preserve-timezone-when-deserializing-datetime-using-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!