问题
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 theTimeZoneInfo
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