【问题标题】:I want to specify a TimeZone as GMT but create a DateTime that is local (EST);我想将 TimeZone 指定为 GMT,但创建一个本地 (EST) 的 DateTime;
【发布时间】:2015-03-24 15:54:14
【问题描述】:

我想在 GMT 时区中指定一个时间,然后将其转换为本地时区,即 EST。

这似乎可以满足我的要求,但似乎还有很长的路要走!

有没有更简单的方法来实现这一点:

public static TimeZoneInfo edtZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    public static TimeZoneInfo gmtZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    public static CultureInfo ci = CultureInfo.InvariantCulture;

 DateTime edtStartDT = TimeZoneInfo.ConvertTime(DateTime.SpecifyKind(DateTime.Now.Date.Add(new TimeSpan(18, 00, 00)), DateTimeKind.Unspecified), gmtZone, edtZone);

【问题讨论】:

  • 给出了一个很好的答案,但澄清问题可能会有所帮助:(A) 你是真的指 GMT 还是真的指 UTC?你是明确想要东部标准时间,还是真的想要当地时间(恰好是东部时间)?如果您在芝加哥运行此项目,您是否仍要使用 Eastern 或 Central?

标签: c# datetime timezone


【解决方案1】:

可能就是你要找的东西:

// A timespan isn't really a time-of-day, but we'll let that slide for now.
TimeSpan time = new TimeSpan(18, 00, 00);

// Use the current utc date, at that time.
DateTime utcDateTime = DateTime.UtcNow.Date.Add(time);

// Convert to the US Eastern time zone.
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime easternDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tz);

请注意,我们将当前 UTC 日期与您提供的时间配对。由于美国东部时间比 UTC 晚 5 或 4 小时,因此 18:00 您将始终获得相同的日期。但如果您使用不同的时间,例如 00:00,您会发现生成的东部时间是 天。这是正常的。

关于您之前的代码的几点说明:

  • Windows 时区 ID "Eastern Standard Time" 指的是EST 和 EDT。它真的应该被称为“东部时间”。不要让名称混淆问题。

  • GMT 和 UTC 对于所有现代用法基本相同。除非您指的是伦敦使用的时区,否则您应该更喜欢 UTC 一词。

  • Windows 时区 ID "GMT Standard Time" 实际上并不适用于 GMT/UTC。它特别是在伦敦使用的时区,在 GMT (UTC+00:00) 和 BST (UTC+01:00) 之间交替。如果您想要一个代表 UTC 的 TimeZoneInfo,则 ID 就是“UTC”。 (但是,在这种情况下,您实际上并不需要它。)

  • 假设您的原始代码使用了DateTime.Now.Date,这将假设计算机本地时区中的日期 - 可能不是 UTC 或东部时间。

  • 如果您发现自己使用DateTime.SpecifyKind,在大多数情况下,您可能做错了什么。 (加载或反序列化时例外。)

关于我关于 TimeSpan 不是真正的时间的注释,这就是 .NET 将如何处理它:

DateTime time = DateTime.Parse("18:00:00", CultureInfo.InvariantCulture);
DateTime utcDateTime = DateTime.UtcNow.Date.Add(time.TimeOfDay);

甚至更丑的一行:

DateTime utcDateTime = DateTime.Parse("18:00:00", CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

就个人而言,我更愿意使用Noda Time,它有一个单独的LocalTime 类型,明确地用于不受特定日期约束的时间。我也在努力获取System.TimeOfDateSystem.Date 类型added to the CoreCLR

【讨论】:

  • 可以将time 命名为offset,而不用担心一天中的某个时间。但是通过观看您自己的 PluralSight 培训和阅读 NodaTime,我只想指出 GMT 与 UTC 不同。我是从你那里学来的。我只是猜测您在猜测 OP 说 GMT 时实际上是指 UTC,但如果他没有,那么您的答案是错误的。
  • @RickDavin - 嗯...我想你可能误解了,因为我记得在 PS 课程中说过 GMT 和 UTC 基本上是相同的,除了它们是如何在法律上定义的以及它们是如何起源的历史。不过很高兴看到你观看! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 2020-10-07
  • 1970-01-01
  • 2013-07-20
  • 2011-07-26
  • 1970-01-01
相关资源
最近更新 更多