.Net 中是否有 ZonedDateTime (Java)? [英] Is there a ZonedDateTime (Java) in .Net?

查看:35
本文介绍了.Net 中是否有 ZonedDateTime (Java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的最佳等效项是 DateTimeOffset + TimeZoneInfo 的组合.创建一个包含这两个类并确保它们保持一致的结构是最好的方法吗?

The best equivalent I've found is the combination of a DateTimeOffset + TimeZoneInfo. Is that the best approach, create a structure that contains both of these classes and insure they stay consistent?

推荐答案

不,.NET 基类库中没有类似于 ZonedDateTime 的内置类型.

No, there is not a built-in type similar to ZonedDateTime in the .NET base class library.

正如其他人指出的那样,如果您正在寻找类似于 Java 的 Joda Time 或 java.time 的时间模型,请考虑使用 野田时间.它有一个 ZonedDateTime 结构.

As others pointed out, if you're looking for a temporal model similar to Java's Joda Time or java.time, then consider using Noda Time. It has a ZonedDateTime structure.

如果您不想使用 Noda Time,并且您确实需要一个包含日期时间偏移和时区的对象,那么您建议使用 DateTimeOffsetTimeZoneInfo 结构的方法 字段是有道理的.以下是一些额外的提示:

If you don't want to use Noda Time, and you really need a single object containing date time offset and time zone, then your suggested approach of a struct with DateTimeOffset and TimeZoneInfo fields makes sense. Here are some additional tips:

  • 将其设计为不可变结构很重要,换句话说 - 仅从构造函数获取输入.仅在字段上公开属性 getter.不要直接暴露字段,也不要在属性上提供 setter.

  • It's important you design this as an immutable struct, in otherwords - take input only from the constructor. Expose only property getters over the fields. Don't expose the fields directly, and don't provide setters on the properties.

注意您希望如何处理 DateTimeOffset 的偏移量不是给定时区的正确偏移量的情况.您可能想要调整它,或者您可能想要抛出异常.

Be aware of how you want to handle situations where the offset of a DateTimeOffset is not the correct offset for the given time zone. You may want to adjust it, or you may want to throw an exception.

您可能需要为您的结构提供自定义序列化,如果保存到数据库,您可能需要解构它.在任一场景中,仅保留 TimeZoneInfo 组件的字符串 Id.不要尝试序列化或存储整个对象.

You may need to provide custom serialization for your struct, and you may need to deconstruct it if saving to a database. In either scenario, keep only the string Id of the TimeZoneInfo component. Don't try to serialize or store the entire object.

也就是说 - 如果您需要这样的对象,您可能需要重新考虑.在许多情况下,单独使用 DateTimeOffsetTimeZoneInfo 就足够了.

That said - you might want to reconsider if you need such an object. In many cases, simply using the DateTimeOffset and TimeZoneInfo separately are sufficient.

这篇关于.Net 中是否有 ZonedDateTime (Java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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