我对LocalDateTime在NodaTime中的命名感到困惑。阅读这些文件后,它似乎是这样写的:
LocalDateTime值并不表示全局时间线上的瞬间,因为它没有关联的时区。
因此,我的理解是:
“如果我在夏令时创建了一个
LocalDateTime,这并不重要,因为这个LocalDateTime不了解TimeZone,因此也就没有与UTC相抵消的信息。”
因此,如果我想将该LocalDateTime转换为UTC,我必须这样做:
// We can't convert directly to UTC because it doesn't know its own offset from UTC.
var dt = LocalDateTime.FromDateTime(DateTime.SpecifyKind(myDt, DateTimeKind.Unspecified));
// We specify the timezone as Melbourne Time,
// because we know this time refers to Melbourne time.
// This will attach a known offset and create a ZonedDateTime.
// Remember that if the system time variable (dt) is in daylight savings, it doesn't
// matter, because LocalDateTime does not contain such information.
// Therefore 8:00 PM in Daylight Savings and 8:00 PM outside of daylight savings
// are both 8:00 PM when we created the ZonedDateTime as below.
var melbCreatedTime = createdTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Australia/Melbourne"]);
// Now we can get to UTC, because we have a ZonedDateTime and therefore
// have a known offset from UTC:
sharedB.CreatedUTC = melbCreatedTime.ToDateTimeUtc();这是正确的吗?到目前为止,DateTime逻辑是我最薄弱的领域,我只想确保我了解这里发生了什么。
不作评论:
var dateCreatedLocal = LocalDateTime.FromDateTime(DateTime.SpecifyKind(result.DateCreated.Value, DateTimeKind.Unspecified));
var dateCreatedUtc = dateCreatedLocal.InZoneLeniently(DateTimeZoneProviders.Tzdb["Australia/Melbourne"]).ToDateTimeUtc();
sharedB.CreatedUTC = dateCreatedUtc;谢谢。
发布于 2019-09-04 08:14:21
没有“日光节约中的LocalDateTime”的概念。它只是一个日期和时间,没有引用任何可能或不可能正在观察DST的时区。
但是,如果您的目标仅仅是使用特定的时区从DateTime和Kind of Unspecified过渡到DateTime和Kind of Utc,我通常建议使用TimeZoneInfo --除非您特别需要IANA时区ID支持。
一般来说,我建议在任何地方都使用Noda时间类型--或者如果要在任何地方使用BCL类型,就不要使用Noda时间。在有些情况下,只为一段孤立的代码使用Noda时间是有意义的,如果您真的需要在这里这样做,那么我认为您的代码应该很好--但是当涉及到夏时制更改(或其他偏移更改)时,请注意InZoneLeniently的含义。
https://stackoverflow.com/questions/57778936
复制相似问题