Convert a time to the time in a particular time zone in CSharp

Description

The following code shows how to convert a time to the time in a particular time zone.

Example


//w w w  .  ja  va 2s  .co  m
using System;

public class Example
{
   public static void Main()
   {
      // Define times to be converted.
      DateTime time1 = new DateTime(2014, 1, 1, 12, 1, 0);
      DateTime time2 = new DateTime(2014, 11, 6, 23, 30, 0);
      DateTimeOffset[] times = { new DateTimeOffset(time1, TimeZoneInfo.Local.GetUtcOffset(time1)),
                                 new DateTimeOffset(time1, TimeSpan.Zero),
                                 new DateTimeOffset(time2, TimeZoneInfo.Local.GetUtcOffset(time2)),
                                 new DateTimeOffset(time2.AddHours(3), TimeZoneInfo.Local.GetUtcOffset(time2.AddHours(3))) };

      // Retrieve the time zone for Eastern Standard Time (U.S. and Canada).
      TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

      // Display the current time zone name.
      Console.WriteLine("Local time zone: {0}\n", TimeZoneInfo.Local.DisplayName);

      // Convert each time in the array. 
      foreach (DateTimeOffset timeToConvert in times)
      {
         DateTimeOffset targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
         Console.WriteLine("Converted {0} to {1}.", timeToConvert, targetTime);
      }                        
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var