I'm trying to Find a timezone and return time with DaylightSavingTime applied?
Currenty I can:
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.
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.
I'm jumping in a bit late here, but I'm not sure why you're doing this all manually. Could not your entire function be replaced by:
public static DateTime GetLocalTime(string TimeZoneName)
{
return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With