How to get the time in another location programatically in .NET?
How can I obtain the time in another UTC location, or at least what UTC time value is set in the computer so I c开发者_开发百科an increase/decrease the current time and obtain what I want?
My specific problem is:
I'm in a specific location, and I want to know what time is in UK.
I finally found the answer. This article explains TimeZoneInfo
and TimeZone
very well, and it has some examples of converting between times of different timezones.
All you need to know is the ID of the Time Zone you want to convert to.
An example (taken from the site):
DateTimeOffset nowDateTime = DateTimeOffset.Now;
DateTimeOffset newDateTime = TimeZoneInfo.ConvertTime(
nowDateTime,
TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"));
Console.WriteLine("Now: {0}", nowDateTime);
Console.WriteLine("Now in Hawaii: {0}", newDateTime);
prints
Now: 3/5/2011 6:30:48 PM -08:00
Now in Hawaii: 3/5/2011 4:30:48 PM -10:00
To obtain a list of all the IDs, you can:
- Check on
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones
- Query
TimeZoneInfo.GetSystemTimeZones();
精彩评论