[英]How to handle UTC difference while converting DateTime
當我嘗試將日期轉換為AST,然后將其轉換回IST時,為什么會相差1小時?
var tesDate = DateTime.Parse("2015-09-01T03:30:00+05:30");
TimeZoneInfo tmz = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
DateTime tesDate1 = DateTime.SpecifyKind(tesDate, DateTimeKind.Unspecified);
var earliestStartTime = TimeZoneInfo.ConvertTime(tesDate1, tmz, TimeZoneInfo.Utc);
//Local Time is Now in IS
var localEarliestStartTime = earliestStartTime.ToLocalTime();
實際輸出{2015年9月1日,12:00:00 PM}
預期輸出{2015/9/1下午}
當我嘗試將日期轉換為AST,然后將其轉換回IST時,為什么會相差1小時?
因為您實際上並沒有進行該轉換。 您正在做一些更復雜的事情,但我不確定為什么。 我將注釋您的代碼,以便您可以看到自己在做什么:
// Parse a string with a fixed +05:30 Indian offset
// This is converting to the local time zone in the process (Kind == DateTimeKind.Local)
var tesDate = DateTime.Parse("2015-09-01T03:30:00+05:30");
// Get the Atlantic time zone
TimeZoneInfo tmz = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
// Assign DateTimeKind.Unspecified, which removes the existing Local kind (why?)
DateTime tesDate1 = DateTime.SpecifyKind(tesDate, DateTimeKind.Unspecified);
// Convert to UTC, pretending the time is in AST, when actually it's in the local zone
var earliestStartTime = TimeZoneInfo.ConvertTime(tesDate1, tmz, TimeZoneInfo.Utc);
// Convert from UTC back to the local zone
var localEarliestStartTime = earliestStartTime.ToLocalTime();
這有點愚蠢,當然會導致錯誤的值。 如果您的目標是將IST轉換為AST,然后再轉換為AST,則應該執行以下操作:
TimeZoneInfo tzAtlantic = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
TimeZoneInfo tzIndian = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTimeOffset original = DateTimeOffset.Parse("2015-09-01T03:30:00+05:30");
DateTimeOffset atlantic = TimeZoneInfo.ConvertTime(original, tzAtlantic);
DateTimeOffset indian = TimeZoneInfo.ConvertTime(atlantic, tzIndian);
除非您有其他未解釋的用途,否則無需涉及UTC或當地時區。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.