本文介绍了使用JSON.NET反序列化DateTime时如何保留时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON.NET在C#中解析一些JSON. JSON中的一个字段是日期/时间,如下所示:

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 ...
}

请注意,时间部分为07:15:11(格林尼治标准时间5时).

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

我从这样的流中解析JSON:

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);
     //...
  }

然后访问时间:

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

但是,这给了我这个DateTime对象:

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

我需要知道原始的当地时间和tz偏移,但是我似乎在反序列化过程中丢失了该信息,这给了我我认为是当地时间的时间(我在英国) ,所以目前是格林尼治标准时间+0).

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?

添加了有关我如何反序列化的更多详细信息.

added more detail about how I'm deserializing.

推荐答案

我会使用代替. DateTime没有任何有用的时区信息.

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

您可以通过更改serializer.DateParseHandling来反序列化为DateTimeOffset:

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

示例: https://dotnetfiddle.net/I9UAuC

这篇关于使用JSON.NET反序列化DateTime时如何保留时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:23