【问题标题】:Convert same time to different time zone将同一时间转换为不同时区
【发布时间】:2014-03-23 14:48:51
【问题描述】:

我正在尝试将时间转换为不同的时区,但不是您的想法。例如,我需要将美国东部标准时间上午 9 点的日期时间转换为 UTC 时间上午 9 点。时区是可变的,因此使用 NodaTime 仅添加/减去小时似乎不是正确的方法

Fri, 21 Feb 2014 21:00:00 EST = 1393034400 Epoch Timestamp
convert to
Fri, 21 Feb 2014 21:00:00 CST = 1393030800 Epoch Timestamp

【问题讨论】:

  • 请在此时发布您必须执行此操作的任何代码。
  • 你的意思是美国东部时间晚上 9 点到中部时间晚上 8 点?
  • 例如,我需要根据 UTC 将 9pm EST(或任何区域)转换为 9pm Central(或任何区域)

标签: c# timezone nodatime


【解决方案1】:

如果我正确理解了这个问题,听起来您正试图将一个时区的日期/时间转换为另一个具有相同本地时间和不同时区的日期/时间;也就是说,不同的时间点。

您可以通过将LocalDateTime 与新区域结合使用 Noda Time 来做到这一点。例如,给定如下内容:

Instant now = SystemClock.Instance.Now;
DateTimeZone eastern = DateTimeZoneProviders.Tzdb["America/New_York"];
ZonedDateTime nowEastern = now.InZone(eastern);

nowEastern 是America/New_York 时区的现在时间。如果我们将nowEastern 直接打印到控制台,我们会看到类似2014-02-22T05:18:50 America/New_York (-05) 的内容。

顺便说一句,“EST”和“CST”不是时区:它们是时区内特定偏移量的非唯一缩写; America/New_York 和 America/Chicago 可能代表了我们所认为的“东部”和“中部”(如果你真的想要 EST,即使夏令时生效,你也可以使用类似 UTC-05:00 的东西)。

给定任意时区的ZonedDateTime,我们可以将其转换为具有相同本地时间和指定时区的ZonedDateTime,如下所示:

DateTimeZone central = DateTimeZoneProviders.Tzdb["America/Chicago"];
ZonedDateTime sameLocalTimeCentral = nowEastern.LocalDateTime.InZoneStrictly(central);

这给了我们一个ZonedDateTime,它的当地时间相同,但时区不同。使用上面的输入,结果将是2014-02-22T05:18:50 America/Chicago (-06)。

请注意,我使用的是InZoneStrictly。如果本地时间不明确或无效(例如,在夏令时转换期间),这将 throw an exception。如果这是不可接受的,您可以使用InZoneLeniently,它会在给定的本地时间或之后选择最早的有效ZonedDateTime,或InZone,它允许您在这些情况下指定自己的规则。

【讨论】:

  • 是的!谢谢你太棒了
【解决方案2】:

在 Msdn website 你可以找到你需要的一切。

小例子:

DateTime dateNow = DateTime.Now;
Console.WriteLine("The date and time are {0} UTC.", 
               TimeZoneInfo.ConvertTimeToUtc(dateNow));

转到链接以获取有关您想要的更多详细信息,我无法为您提供更多详细信息

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2015-11-27
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多