JSON 如何反序列化日期时间并从 UTC 转换为指定的时区? [英] How JSON deserialize datetime and convert from UTC to a specified time zone?

查看:38
本文介绍了JSON 如何反序列化日期时间并从 UTC 转换为指定的时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个自定义的 json 序列化程序,它将具有 dateTime 的对象与 UTC 和从 UTC 转换并返回到指定的时区.(非本地)

I want to create a custom json serializer that will convert objects with dateTime to and from UTC and back to a specified time zone. (Not local)

转换为UTC的例子是:

Example which converts to UTC is:

MyObject stuff = new MyObject();
stuff.Date = DateTime.Now;

string asdd = JsonConvert.SerializeObject(stuff,
            new JsonSerializerSettings()
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            });

如何通过 JsonSerializerSettings 或自定义序列化程序从 UTC 转换回特定时区?

How do I convert from UTC back to a specific timezone via JsonSerializerSettings or a custom serializer?

注意:我在 .NET Core 2.1 中工作.

Note: I'm working in .NET Core 2.1.

推荐答案

不应在序列化或反序列化时处理时区转换.这些是不同的关注点.

Time zone conversion should not be handled at time of serialization or deserialization. Those are separate concerns.

相反:

保留 DateTimeZoneHandling 的默认值 RoundtripKind.(不要将其设置为 Utc.)这具有以下行为:

Leave DateTimeZoneHandling at its default of RoundtripKind. (Don't set it to Utc.) This has the behavior of:

  • 如果您反序列化为 DateTime,并且在您的数据中没有传递偏移量,则 DateTimeKind.Unspecified 将被设置.
  • 如果您反序列化为 DateTime,并在数据中传递尾随 Z,则 DateTimeKind.Utc 将被设置.
  • 如果您要反序列化为 DateTime,并在您的数据中传递一个偏移量,那么将设​​置 `DateTimeKind.Local,并将该值转换为本地时区(通常应该避免这种情况).
  • 如果您反序列化为 DateTimeOffset,那么偏移量将被持久化并且值不会改变(如果传递偏移量,这是更好的方法).
  • If you are deserializing to a DateTime, and passing no offset in your data, then DateTimeKind.Unspecified will be set.
  • If you are deserializing to a DateTime, and passing a trailing Z in your data, then DateTimeKind.Utc will be set.
  • If you are deserializing to a DateTime, and passing an offset in your data, then `DateTimeKind.Local will be set, and the value will be converted to the local time zone (generally one should avoid this).
  • If you are deserializing to a DateTimeOffset, then the offset will be persisted and the value will not change (this is the better approach if passing offsets).

一旦你有一个 DateTimeDateTimeOffset 值,然后使用 TimeZoneInfo.ConvertTime 和类似的方法在必要时更改时区.这部分应该在您的应用程序代码中,因为它往往特定于特定 API 的逻辑.

Once you have a DateTime or DateTimeOffset value, then use TimeZoneInfo.ConvertTime and similar methods to change time zones if necessary. This part should be in your application code, as it tends to be specific to the logic of a particular API.

一般来说,这是一种反模式(违反 SRP)试图处理所有传入或无论是通过序列化还是其他某种机制,传出日期/时间数据都位于同一时区.

Generally speaking, it's an antipattern (SRP violation) to try to treat all incoming or outgoing date/time data to be in the same time zone, whether via serialization or some other mechanism.

这篇关于JSON 如何反序列化日期时间并从 UTC 转换为指定的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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