未按预期计算时区偏移量

TimeZone Offset not calculated as expected

我有一些这样的代码

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 小时。有什么想法吗?

这里有几个问题:

  • 东部标准时间有 -5 小时的 base 偏差。但是,它在那个特定的日期时间经历了夏令时

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 小时。