I have a scenario where I have a timezone offset (in minutes) and need to determine the timezone for it. I know that all the data is not available (for example, there may be several timezones with an offset of -240 minutes) but a "best guess" is acceptable.
My first pass looked like this:
foreach (var info in TimeZoneInfo.GetSystemTimeZones())
{
if (info.BaseUtcOffset.TotalMinutes == timezoneOffset)
{
// do something here if this is a valid timezone
}
}
This sorta works, but I need to account for daylight savings which is throwing me off somewhat. I added this terrible hack:
foreach (var info in TimeZoneInfo.GetSystemTimeZones())
{
var extra = info.IsDaylightSavingTime(DateTime.Now) ? 60 : 0;
if (info.BaseUtcOffset.TotalMinutes + extra == timezoneOffset)
{
// do something here if this is a valid timezone
}
}
This works "well enough" in that I can show the user the correct time for them when daylight savings is not in effect and am about 70% correct during DST. Still... this is some awful code to my eyeballs.
Is there a better way to do this? More elegance would be good, and more accuracy would be better still.
Update
Technically I have access to any information Javascript can get regarding the date. I have a page on which I've placed a hidden field called "offset". I have a JQuery function that populates the offset field with the DateTime().getTimezoneOffset(). While I don't see anything on the DateTime object that will help, perhaps this will open other avenues for ideas.