Determine if UTC Time is in DST for a given Timezone
I have a time, in UTC. I also have a "Room" assignment, which has partial timezone information associated with it (it's got a location, so I know if it's Eastern, Pacific, etc).
I need to take the UTC time, and convert it to the "target" timezone开发者_StackOverflow中文版. However, the date could be in the future or the past, so the "target" timezone needs to be "Standard" or "Daylight" according to the appropriate timezone rules.
So, I want something like this:
TimeZoneInfo.ConvertTimeFromUtc(UTCDateTime, TimeZoneInfo.FindSystemTimeZoneById(tz));
But I don't know how to get "tz", since all I know is that it's (for example) a PST or PDT value, I don't know which one.
How should I approach this?
You always pass the name of the standard (non daylight savings enabled) time zone. In your case that's "Pacific Standard Time".
To find these names look in your machine's registry with Regedit.exe. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. Beware that this list is only deemed reliable for Windows Vista and up, your code isn't going to work well for earlier versions (2000 and XP). The one feature that is missing is historic information about previous changes to the daylight savings rule. The "Dynamic DST" subkey. The machine must also have Windows Update enabled to receive updates to these rules.
And of course it doesn't keep track at all over local political decisions about DST rules. Common in the USA for example for counties in Indiana, Arizona and American Indian tribal territories.
I don't think it's possible given the information you have. Even though you know the location the problem is time zones aren't a 1:1 mapping to a specific country so you can't assume which timezone it is going to be.
There are webservices out there that allow you to query Timezone information based on a city/postcode and other info, that might be your only alternative.
Since you already know the zone and you have the UTC time in a TimeZoneInfo object, after you convert, apply the IsDaylightSavingTime(UTCDateTime) method to determine whether standard or daylight saving time applies to your local time.
If you want the name for the appropriate local time (e.g. PST or PDT), you can get them from the StandardName and DaylightName properties.
There are some warnings in the Microsoft online documentation regarding behavior on ambiguous times and Windows XP platform.
精彩评论