处理时区时间

Handling Time over TimeZones

我正在尝试将此字符串时间值 2017-01-10T13:19:00-07:00 转换为本地时间(东部时间)。现在根据我的研究,07:00Mountain Time,比 Eastern Time(我的本地)晚了 2 小时。但是,当我 运行 这种语法转换返回的输出是 01/17/2017 10:19:00 AM 这是 3 小时的差异,而不是 2。

这是我正在使用的语法,这个设置不正确吗?我应该更改什么才能从 UTC 时间返回准确的本地时间?

static void Main(string[] args)
{
    string green = "2017-01-10T13:19:00-07:00";

    DateTime iKnowThisIsUtc = Convert.ToDateTime(green);
    DateTime runtimeKnowsThisIsUtc = DateTime.SpecifyKind(
        iKnowThisIsUtc,
        DateTimeKind.Utc);
    DateTime localVersion = runtimeKnowsThisIsUtc.ToLocalTime();
    Console.WriteLine(localVersion);
    Console.ReadKey();
}

编辑
我已使用以下语法验证我的计算机设置为正确的时区,该语法为两者生成东方(正确)

TimeZone zone = TimeZone.CurrentTimeZone;
string standard = zone.StandardName;
string daylight = zone.DaylightName;
Console.WriteLine(standard);
Console.WriteLine(daylight);

将字符串转换为 DateTime 对象:

var datetime = DateTime.Parse("2017-01-10T13:19:00-07:00");

获取 EST 的时区:

var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

转换为 EST(注意转换 .ToUniversalTime()):

var easternTime = TimeZoneInfo.ConvertTimeFromUtc(datetime.ToUniversalTime(), easternZone);

easternTime.ToString(); 的输出:

10/01/2017 15:19:00

(我在英国,因此 dd/MM/yyyy,你的显示可能不同)

当您的应用程序需要明确了解时区时,您可能需要考虑使用 DateTimeOffset 而不是 DateTime。

Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo

这个问题看起来有人收集了很多关于这个主题的最佳实践 - [​​=11=]

// your input string
string green = "2017-01-10T13:19:00-07:00";

// parse to a DateTimeOffset
DateTimeOffset dto = DateTimeOffset.Parse(green);

// find the time zone that you are interested in.
// note that this one is US Eastern time - inclusive of both EST and EDT, despite the name.
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

// convert the DateTimeOffset to the time zone
DateTimeOffset eastern = TimeZoneInfo.ConvertTime(dto, tzi);

// If you need it, you can get just the DateTime portion.  (Its .Kind will be Unspecified)
DateTime dtEastern = eastern.DateTime;