c# - 将 UTC 转换为东部时区

标签 c# timezone

我有一个 UTC 时间戳(字符串类型)。我希望将此时间戳转换为东部时间。问题是当我在 UTC 时间戳上调用 DateTime.Parse 或 Convert.ToDateTime 时,它​​会将其转换为我的本地时间,即中部时间。

如何获取字符串时间戳并将其转换为东部时间,而不管其运行的服务器的本地时间如何?

最佳答案

我会尝试剖析你的问题,但下次请展示一些代码,以便每个人都能更清楚地理解你的意思。

I have a UTC timestamp coming in UTC (string type).

好吧,我想你的意思是这样的:

string utcString = "2014-02-25T12:34:56.000Z";

这是一个 ISO-8601 UTC 时间戳。如果是其他格式,请在评论中告诉我,我会相应地更新答案。

... The problem is when I call DateTime.Parse or Convert.ToDateTime on the UTC timestamp, it is converting it to my local time, which is Central Time.

DateTime utcDateTime = DateTime.Parse(utcString,
                                      CultureInfo.InvariantCulture,
                                      DateTimeStyles.RoundtripKind);

RoundtripKind 样式告诉解析器在输入字符串中查找“种类”信息,例如指示 UTC 的 Z。生成的 DateTime 将具有原始值,并且它的 .Kind 属性设置为 DateTimeKind.Utc

... I want this timestamp to be converted to Eastern Time.

现在您有了 UTC DateTime,您可以使用 TimeZoneInfo 类轻松转换它。

TimeZoneInfo easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById(
                                                         "Eastern Standard Time");

DateTime easternDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime,
                                                           easternTimeZone);

就是这样。结果是包含美国东部时区本地时间的 DateTime。它是 Unspecified,因为时区信息不随 DateTime 对象一起携带。

另请注意,“东部标准时间”是指整个美国东部时区,包括 EST 和 EDT。

关于c# - 将 UTC 转换为东部时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029004/

相关文章:

javascript - 如何在 JavaScript 中确定系统的 Olson zoneinfo?

java - 在 Java 8 上为 Maven 单元测试设置时区

javascript - 在网站上显示准确的本地时间?

ruby-on-rails - Rails : Hack Time. 现在别名为 Time.current

c# - 分析代码覆盖消失

c# - 大O分析。非负数组中的最大整数

c# - 查找带有标签的非事件游戏对象?

c# - Thread Join() 导致 Task.RunSynchronously 未完成

c# - 在数据库优先方法中为 Entity Framework 5 中的所有实体创建基类

java - 如何更改 Java 的 ZonedDateTime 中的时区