【问题标题】:Serialize datetime lost information about timeZone with zulu format使用zulu格式序列化日期时间丢失有关时区的信息
【发布时间】:2019-06-20 16:24:11
【问题描述】:

当我尝试使用 JObject (Newtonsoft) 时,我丢失了一些 zulu 日期格式的数据

var s = "{  \"DateTimeZulu\": \"2019-06-12T08:50:20.626Z\",  \"DateTimeUtc\": \"2019-06-12T08:50:20.626+00:00\" }";
var jsonEntity = (JObject.Parse(s));
foreach (KeyValuePair<string, JToken> current in jsonEntity)
{
    Console.WriteLine(current.Key + " - " + current.Value.ToString());
}

实际输出:

DateTimeZulu - 12/06/2019 08:50:20  
DateTimeUtc - 12/06/2019 10:50:20  

预期输出:

DateTimeZulu - 12/06/2019 10:50:20  
DateTimeUtc - 12/06/2019 10:50:20  

【问题讨论】:

  • 您可以强制 Json.Net 使用 DateTimeOffset 而不是保留时区的 DateTime,因为 DateTime 没有时区的概念。您可以使用JsonConvert.DeserializeObject&lt;JObject&gt;(s, new JsonSerializerSettings { DateParseHandling = DateParseHandling.DateTimeOffset }) 来执行此操作。这将为两者正确生成12/06/2019 08:50:20(而不是12/06/2019 10:50:20)。

标签: c# json.net datetime-format utc


【解决方案1】:

信息不会丢失。如果您检查current.Value 的内容,您会看到Kind 属性的差异。

第一个值类型是UTC,第二个值类型是Local。如果影响日期如何转换为字符串。

您可以使用 ToUniversalTimeToLocalTime 函数在 UTC 和本地之间转换 DateTime。请尝试以下示例以查看差异:

    var s = "{  \"DateTimeZulu\": \"2019-06-12T08:50:20.626Z\",  \"DateTimeUtc\": \"2019-06-12T08:50:20.626+00:00\" }";
    var jsonEntity = (JObject.Parse(s));
    foreach (KeyValuePair<string, JToken> current in jsonEntity)
    {  
        Console.WriteLine(current.Key + " - " + ((DateTime)current.Value).ToLocalTime().ToString());
        Console.WriteLine(current.Key + " - " + ((DateTime)current.Value).ToUniversalTime().ToString());
    }

【讨论】:

  • 坦克,如果我能解决我的问题,我明天会用善良的财产看一看!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多