views:

35

answers:

1

Hello I'm trying to Find a timezone and return time with DaylightSavingTime applied?

Currenty I can:

  1. find the time zone
  2. get utc offset
  3. calculate the local time based on that
  4. determine if the time zone uses DaylightSavingTime
  5. get the rules for DaylightSavingTime
  6. determine if the current time uses DaylightSavingTime

However I'm having issues applying the rules, here's the code:

fyi

System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient) returns = 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;

The final value localDate of is {2010/07/10 08:20:40 AM}

It should be {2010/07/10 09:20:40 AM}

It's 1 hour off for some reason.

+1  A: 

ok, I fixed it:

 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;
    }

To test it you can do this:

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

then do a quickwatch on "list" at the end and go to worldtimeserver.com and confirm a few cities.

aron