2017-04-18 25 views
1

我有這樣時區按預期

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年6月9日23時三十零比原始的,而不是5小時偏移少2小時將表明。有任何想法嗎?

+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不specifiy一個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小時。