与NodaTime中'LocalDateTime'的命名混淆

Confusion with the naming of 'LocalDateTime' in NodaTime

我对 NodaTime 中 LocalDateTime 的命名感到困惑。 阅读文档,它似乎说:

A LocalDateTime value does not represent an instant on the global time line, because it has no associated time zone

因此,我将其解释为:

"If I create a LocalDateTime in daylight savings, it doesn't matter, because this LocalDateTime has no knowledge of TimeZone and therefore no known offset from 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;

谢谢。

没有“LocalDateTime 夏令时”的概念。 只是一个日期和时间,没有提及任何可能遵守或不遵守夏令时的时区。

但是,如果您的目标只是从 KindUnspecifiedDateTimeKindUtc 使用特定时区,我 通常 建议使用 TimeZoneInfo - 除非您特别需要 IANA 时区 ID 支持。

一般来说,我建议在任何地方都使用 Noda Time 类型 - 或者如果您要在任何地方使用 BCL 类型,则根本不要使用 Noda Time。在某些情况下,仅对一段孤立的代码使用 Noda Time 是有意义的,如果您真的需要 在这里这样做,那么我相信您的代码应该没问题 - 但是当谈到围绕夏令时变化(或其他偏移量变化)的模糊或跳过的当地时间时,请注意 InZoneLeniently 的含义。