与NodaTime中“ LocalDateTime”的命名混淆

时间:2019-09-03 21:26:34

标签: c# nodatime

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

  

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;

谢谢。

1 个答案:

答案 0 :(得分:1)

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

但是,如果您的目标只是从DateTime的{​​{1}}到{{1}的Kind的{​​{1}} }}使用特定的时区,通常 建议使用Unspecified-除非您特别需要IANA时区ID支持。

通常,我建议在任何地方都使用Noda Time类型-否则,如果您要在所有地方都使用BCL类型,则完全不要使用Noda Time。在某些情况下,仅将Noda Time用于单独的一段代码是有意义的,并且如果您真的需要在此处执行此操作,那么我相信您的代码应该没问题-但请注意DateTime在夏令时更改(或其他偏移量更改)周围的时间不明确或跳过时的含义。

相关问题