Mega Code Archive

 
Categories / C# / Date Time
 

Converts a time to the time in a particular time zone

using System; public class Example {    public static void Main()    {       DateTime[] times = { new DateTime(2010, 1, 1, 0, 1, 0),                             new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Utc),                             new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Local)};       TimeZoneInfo est;        try {          est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");       }       catch (TimeZoneNotFoundException) {          Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");          return;       }       catch (InvalidTimeZoneException) {          Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");          return;       }          Console.WriteLine("Local time zone: {0}\n", TimeZoneInfo.Local.DisplayName);       foreach (DateTime timeToConvert in times)       {          DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);          Console.WriteLine("Converted {0} {1} to {2}.", timeToConvert, timeToConvert.Kind, targetTime);       }                            } }