处理时区的时间

时间:2017-01-20 14:06:16

标签: c# datetime utc

我正在尝试将此字符串时间值2017-01-10T13:19:00-07:00转换为本地时间(东部)。现在我的研究07:00Mountain Time,这是2小时beind Eastern Time(我的当地人)。但是,当我运行此语法来转换返回的输出为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);

3 个答案:

答案 0 :(得分:1)

将字符串转换为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,你的可能会有不同的表现)

答案 1 :(得分:1)

// 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;

答案 2 :(得分:0)

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

Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo

这个问题看起来有人收集了很多关于这个问题的最佳实践 - Daylight saving time and time zone best practices