考虑到夏令时,从一个时区转换为另一个时区

时间:2014-07-16 14:31:02

标签: c# timezone dst

我想将日期时间从一个时区转换为另一个时区。为此,我需要将区域ID传递给方法FindSystemTimeZoneById。但我没有这些信息,需要通过使用开关盒来确定 在这里,我还需要考虑夏令时。但是为了确定时间是否在DST中,我需要事先获得该区域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;

3 个答案:

答案 0 :(得分:0)

检查微软"永恒的"文章Coding Best Practices Using DateTime in the .NET Framework

该文章可能已有几年历史,但原则和问题场景仍然是今天的主题。

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

  

本地时间视图转换为通用时间之前   执行计算,你就会遇到时间问题   精度。

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

答案 1 :(得分: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

答案 2 :(得分:0)

将源时间转换为UTC时间。

string sourceTimeZone="Atlantic Standard Time;
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZone);
DateTime sourceUTCTime = TimeZoneInfo.ConvertTimeToUtc(currentTime, timeZoneInfo);

然后使用转换后的UTC时间获得以下目标时间,

string destinationTimeZone="India Standard Time";
TimeZoneInfo destTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZone);
DateTime destinationUTCTime = TimeZoneInfo.ConvertTimeFromUtc(sourceUTCTime, destTimeZoneInfo);

希望这会有所帮助!