即使未指定,您能否告诉 JSON.Net 将 DateTime 序列化为 Utc? [英] Can you tell JSON.Net to serialize DateTime as Utc even if unspecified?

查看:26
本文介绍了即使未指定,您能否告诉 JSON.Net 将 DateTime 序列化为 Utc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中的日期存储为 Utc.但是当我使用实体框架检索它们时,它们会以未指定的类型出现.

Dates in my database are stored as Utc. But when I retreieve them w/ the entity framework they come out as type unspecified.

当 JSON.Net 序列化它们时,它们不是 Utc 格式.有没有办法告诉 JSON.Net 将 DateTimes 序列化为 Utc,即使它们的类型没有指定为 Utc?

When JSON.Net serializes them they are not in Utc format. Is there a way to tell JSON.Net to serialize DateTimes as Utc even if their type is not specified as Utc?

推荐答案

JsonSerializerSettings 上的 DateTimeZoneHandling 设置为 Utc.这将在序列化之前将所有日期转换为 UTC.

Set DateTimeZoneHandling on JsonSerializerSettings to Utc. That will convert all dates to UTC before serializing them.

public void SerializeObjectDateTimeZoneHandling()
{
  string json = JsonConvert.SerializeObject(
    new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
    new JsonSerializerSettings
    {
      DateTimeZoneHandling = DateTimeZoneHandling.Utc
    });

  Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
}

文档:DateTimeZoneHandling 设置

这篇关于即使未指定,您能否告诉 JSON.Net 将 DateTime 序列化为 Utc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆