2014-07-16 56 views
0

我想将日期时间从一个时区转换为另一个时区。为此,我需要将区域ID传递给方法FindSystemTimeZoneById。但我没有这些信息,需要通过使用开关盒来确定。
这里我还需要考虑夏令时。但为了确定一个时间是否在夏令时,我需要预先设置防区ID。
有没有什么方法可以确定一个时间是否在没有区域ID的DST中。我的服务器是在1区,我想向区2考虑到夏令时从一个时区转换到另一个时区

这里的时间转换为片段:

public DateTime ConvertToDestTime(DateTime currentTime, string sourceTimeZoneUtc, string serverTimeZoneUtc) 
    { 
     TimeZoneInfo sourceTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ReturnTimeZoneString(sourceTimeZoneUtc)); 
     TimeZoneInfo serverTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ReturnTimeZoneString(serverTimeZoneUtc)); 
     DateTime serverTime = TimeZoneInfo.ConvertTime(currentTime, sourceTimeZone, serverTimeZone); 
     return serverTime; 
    } 

    private string ReturnTimeZone(string utcOffset) 
    { 
     string timezone = string.Empty; 
     string isDaylight = //need to determine whether time is in DST here 

     if (isDaylight == "N") 
     { 
      switch (utcOffset) 
      { 
       case "-04:00": 
        timezone = "Atlantic Standard Time"; 
        break; 
       case "-05:00": 
        timezone = "Eastern Standard Time"; 
        break; 

      } 
     } 
     else 
     { 
      switch (utcOffset) 
      { 
       case "-04:00": 
        timezone = "Eastern Standard Time"; 
        break; 
       case "-05:00": 
        timezone = "Central America Standard Time"; 
        break;      
      } 
     } 

     return timezone; 
+0

''currentTime'你有什么样的价值? (它的'Kind'属性返回什么?) –

+0

它是作为“未指定”而来的。该字段的值为“7/13/2014 12:00:00 AM” – Priyanka

+1

然后TimeZoneInfo应该只为您处理DST。虽然指定一个时间zonr作为UTC偏移通常是一个非常糟糕的主意。 –

回答

0

检查OU牛逼微软的“永恒”的文章Coding Best Practices Using DateTime in the .NET Framework

这篇文章可能会有几年的历史,但是原则和问题场景仍然是今天的话题。

有关于Dealing with Daylight Savings Time的专门章节。

通过之前 转换您本地时间意见通用时间执行你的计算,你过去的时间 精度的问题。

因此,首先将当地时间转换为UTC格式,然后转换为目标时间格式。

0

您无法可靠地执行此类反向映射。只有两个可能的时区可以包含任何特定的偏移量。

  • 请参阅the timezone tag wiki中的“TimeZone!= Offset”。请参阅all the places that -04:00 might be used

  • 最后,要认识到,因为北美的每个时区都会在当地时间倒退,所以某些值会一次被两个时区共享。

    例如,2014-11-02T01:00:00-05:00可能属于或者美国中部时间(CDT)或美国东部时间(EST),as shown here

相关问题