将 System.DateTime 转换为 NodaTime.ZonedDateTime

11

我有一个已经处于特定时区但未指定DateTime.KindSystem.DateTime,以及代表IANA时区的字符串。我希望将其转换为NodaTime.ZonedDateTime

例如:

var original = new DateTime(2016, 1, 1, 12, 0, 0);
var timezone = "America/Chicago";

我想要一个表示芝加哥时间2016年1月1日中午12点的ZonedDateTime。我该如何做到这一点?

1个回答

15

如果我理解正确,您想获取一个具有已知时间的标准DateTime,并获得表示该日期、时间和时区的ZonedDateTime,对吗?

如果是这样,我相信这将实现。如果可以直接构造,从DateTimeLocalDateTime的中间转换可能不是必需的。

var dotNetDateTime = new DateTime(2016, 1, 1, 12, 0, 0);
var localDate = LocalDateTime.FromDateTime(dotNetDateTime);
var chicagoTime = DateTimeZoneProviders.Tzdb["America/Chicago"];
var chicagoZonedDateTime = chicagoTime.AtStrictly(localDate); // Will contain 2016 01 01 noon

// now you can convert to time in Los Angeles
var laTime = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
var laZonedDateTime = chicagoZonedDateTime.WithZone(laTime); // will contain 2016 01 01 10am

3
没问题,这是正确的 - 但你也许应该考虑 AtStrictly 可能没有你要寻找的行为方式。熟悉其他选项,如 AtLeniently,以及自定义解析器,如我在这里展示的 调度解析器(它是2.x中的新宽松解析器)。 - Matt Johnson-Pint

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接