使用 zulu 格式序列化 datetime 丢失的有关 timeZone 的信息
Serialize datetime lost information about timeZone with zulu format
当我尝试使用 JObject (Newtonsoft) 时,我丢失了一些祖鲁日期格式的数据
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
信息没有丢失。如果您检查 current.Value
内容,您会发现 Kind
属性 中的差异。
第一个值种类是UTC
,第二个值种类是Local
。如果影响日期将如何转换为字符串。
您可以使用 ToUniversalTime
或 ToLocalTime
函数在 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());
}
当我尝试使用 JObject (Newtonsoft) 时,我丢失了一些祖鲁日期格式的数据
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
信息没有丢失。如果您检查 current.Value
内容,您会发现 Kind
属性 中的差异。
第一个值种类是UTC
,第二个值种类是Local
。如果影响日期将如何转换为字符串。
您可以使用 ToUniversalTime
或 ToLocalTime
函数在 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());
}