TimeZone Offset未按预期计算

时间:2017-04-18 00:02:42

标签: c# .net timezone-offset

我有一些像这样的代码

string date = "10/06/2017 1:30:00 PM"; // UTC time
var dateValue = DateTime.ParseExact(date, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
string timeZone = "Eastern Standard Time"; // Offset is -5 hours
TimeZoneInfo newTime = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
var result = TimeZoneInfo.ConvertTime(dateValue, newTime).ToString("yyyy-MM-dd HH:mm");

结果输出是2017-06-09 23:30,比原来的少两个小时,而不是偏移所指示的5小时。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这里有几个问题:

  • 东部标准时间的基础偏移量为-5小时。但是,它在特定日期时间遇到夏令时

string timeZone = "Eastern Standard Time"; // Offset is -5 hours

TimeZoneInfo newTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
Console.WriteLine(newTimeZone.BaseUtcOffset); // -5
Console.WriteLine(newTimeZone.IsDaylightSavingTime(dateValue)); // True
  • ParseExact未指定DateTimeKind,默认为unspecified。这意味着它表现为UTC和本地时间,具体取决于您对其执行的操作。我们在这里应该明确表示我们正在讨论UTC时间:

string date = "10/06/2017 1:30:00 PM"; // UTC time
var dateValue = DateTime.ParseExact(date, 
                    "d/MM/yyyy h:mm:ss tt", 
                    CultureInfo.InvariantCulture, 
                    DateTimeStyles.AssumeUniversal);

// Although we specified above that the string represents a UTC time, we're still given 
// A local time back (equivalent to that UTC)
// Note this is only for debugging purposes, it won't change the result of the output   
dateValue = dateValue.ToUniversalTime();

最终代码:

string date = "10/06/2017 1:30:00 PM"; // UTC time
var dateValue = DateTime.ParseExact(date, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

string timeZone = "Eastern Standard Time"; // Offset is -5 hours

TimeZoneInfo newTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
Console.WriteLine(newTimeZone.BaseUtcOffset); // -5
Console.WriteLine(newTimeZone.IsDaylightSavingTime(dateValue)); // True

var result = TimeZoneInfo.ConvertTime(dateValue, newTimeZone);
Console.WriteLine(result);

打印10/06/2017 9:30:00 AM - 比UTC字符串落后4小时。