Is there a ZonedDateTime (Java) in .Net?

社会主义新天地 提交于 2021-02-19 05:19:50

问题


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?


回答1:


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

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.

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:

  • 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.

  • 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.

  • 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.

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.



来源:https://stackoverflow.com/questions/62804207/is-there-a-zoneddatetime-java-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!