如何在转换DateTime时处理UTC差异

时间:2015-09-01 07:35:22

标签: c# .net datetime dst

当我尝试将日期转换为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();
  

Actual OutPut {9/1/2015 12:00:00 PM}

     

预期输出{9/1/2015 01:00:00 PM}

1 个答案:

答案 0 :(得分: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并返回,那么您应该这样做:

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或当地时区,除非您有其他目的,但您没有解释。