如何应用DaylightSavingTime查找时区和返回时间?

时间:2010-07-10 14:31:21

标签: c# datetime timezone utc

我正在尝试使用DaylightSavingTime查找时区和返回时间?

我可以:

  1. 找到时区
  2. 获取utc offset
  3. 根据
  4. 计算当地时间
  5. 确定时区是否使用DaylightSavingTime
  6. 获取DaylightSavingTime的规则
  7. 确定当前时间是否使用DaylightSavingTime
  8. 但是我在应用规则时遇到问题,这里是代码:

    FYI

    System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient) return = 2010/07/10 09:25:45 AM

     DateTime localDate = System.DateTime.Now.ToUniversalTime();
    // Get the venue time zone info
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
    localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);
    
    
    if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
    {
        localDate = localDate.Subtract(tz.GetAdjustmentRules().Single(r => localDate >= r.DateStart && localDate <= r.DateEnd).DaylightDelta);
    }
    DateTimeOffset utcDate = localDate.ToUniversalTime();
    
    
    return localDate;
    

    最终值 localDate 是{2010/07/10 08:20:40 AM}

    应该是{2010/07/10 09:20:40 AM}

    由于某种原因,这是1小时。

2 个答案:

答案 0 :(得分:3)

好吧,我修好了:

 public static DateTime GetLocalTime(string TimeZoneName)
    {
        DateTime localDate = System.DateTime.Now.ToUniversalTime();

        // Get the venue time zone info
        TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName);
        TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
        localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);
        //DateTimeOffset localDate = new DateTimeOffset(venueTime, tz.BaseUtcOffset);

        if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
        {
            TimeZoneInfo.AdjustmentRule[] rules = tz.GetAdjustmentRules();
            foreach (var adjustmentRule in rules)
            {
                if (adjustmentRule.DateStart <= localDate && adjustmentRule.DateEnd >= localDate)
                {
                    localDate = localDate.Add(adjustmentRule.DaylightDelta);
                }
            }
            //localDate = localDate.Subtract(tz.GetAdjustmentRules().Single(r => localDate >= r.DateStart && localDate <= r.DateEnd).DaylightDelta);
        }
        DateTimeOffset utcDate = localDate.ToUniversalTime();


        return localDate;
    }

要测试它,你可以这样做:

Hashtable list = new Hashtable();
        foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones())
        {
            string name = tzi.DisplayName;
            DateTime localtime = TimeZoneHelper.GetLocalTime(tzi.Id);
            list.Add(name, localtime);
        }

然后在最后的“列表”上做一个快速观察并转到worldtimeserver.com并确认几个城市。

答案 1 :(得分:3)

我在这里跳了一下,但我不确定你为什么要手动完成这一切。您的整个功能无法替换为:

public static DateTime GetLocalTime(string TimeZoneName)
{
  return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName));
}