将 DateTimeKind.Unspecified 的日期时间从 utc 转换为本地
Convert DateTime with DateTimeKind.Unspecified from utc to local
我有一个数据库,其中所有日期都是 UTC,并且驱动程序总是向我发送带有 DateTimeKind.Unspecified
的 DateTime
个对象。我想假设它们是 UTC 时间并转换为本地时间。
使用 NodaTime 实现此目的的最简单方法是什么?
Instant.FromDateTimeUtc(utcDate).InZone(localZone);
一直抱怨 DateTimeKind 应该是 Utc。
如果您确定使用野田时间并想要 ZonedDateTime
,您可以 "tell" 野田时间,您确实有一个 UTC 值,然后转换它:
var zoned = LocalDateTime.FromDateTime(utcDate)
.InZoneStrictly(DateTimeZone.Utc)
.WithZone(localZone);
或者您可以只使用 DateTime.SpecifyKind
开始:
var utcDateTime = DateTime.SpecifyKind(unspecifiedDateTime, DateTimeKind.Utc);
...然后使用您现有的代码,或者如果您愿意,可以完全不使用 Noda Time。
确实,如果您在其他地方不需要野田时间,那么 DateTime.ToLocalTime()
就可以了:
var localDateTime = utcDateTime.ToLocalTime();
... 如果您调用 ToLocalTime()
,BCL 将假定未指定的 date/time 是 UTC。当然,我建议在任何地方都使用 Noda Time :)
Instant now = SystemClock.Instance.GetCurrentInstant();
DateTimeZone TimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
var zoned = LocalDateTime.FromDateTime(msg.MessageSentUtc)
.InZoneStrictly(DateTimeZone.Utc)
.WithZone(TimeZone);
简化...
我有一个数据库,其中所有日期都是 UTC,并且驱动程序总是向我发送带有 DateTimeKind.Unspecified
的 DateTime
个对象。我想假设它们是 UTC 时间并转换为本地时间。
使用 NodaTime 实现此目的的最简单方法是什么?
Instant.FromDateTimeUtc(utcDate).InZone(localZone);
一直抱怨 DateTimeKind 应该是 Utc。
如果您确定使用野田时间并想要 ZonedDateTime
,您可以 "tell" 野田时间,您确实有一个 UTC 值,然后转换它:
var zoned = LocalDateTime.FromDateTime(utcDate)
.InZoneStrictly(DateTimeZone.Utc)
.WithZone(localZone);
或者您可以只使用 DateTime.SpecifyKind
开始:
var utcDateTime = DateTime.SpecifyKind(unspecifiedDateTime, DateTimeKind.Utc);
...然后使用您现有的代码,或者如果您愿意,可以完全不使用 Noda Time。
确实,如果您在其他地方不需要野田时间,那么 DateTime.ToLocalTime()
就可以了:
var localDateTime = utcDateTime.ToLocalTime();
... 如果您调用 ToLocalTime()
,BCL 将假定未指定的 date/time 是 UTC。当然,我建议在任何地方都使用 Noda Time :)
Instant now = SystemClock.Instance.GetCurrentInstant();
DateTimeZone TimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
var zoned = LocalDateTime.FromDateTime(msg.MessageSentUtc)
.InZoneStrictly(DateTimeZone.Utc)
.WithZone(TimeZone);
简化...