Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 can 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.

like image 762
Oscar Mederos Avatar asked Mar 05 '11 22:03

Oscar Mederos


1 Answers

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();
like image 90
Oscar Mederos Avatar answered Sep 21 '22 05:09

Oscar Mederos