我有一个 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
orConvert.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/