C# TimeZoneInfo ConvertTime(DateTimeOffset, TimeZoneInfo)

Description

TimeZoneInfo ConvertTime(DateTimeOffset, TimeZoneInfo) converts a time to the time in a particular time zone.

Syntax

TimeZoneInfo.ConvertTime(DateTimeOffset, TimeZoneInfo) has the following syntax.


public static DateTimeOffset ConvertTime(
  DateTimeOffset dateTimeOffset,
  TimeZoneInfo destinationTimeZone
)

Parameters

TimeZoneInfo.ConvertTime(DateTimeOffset, TimeZoneInfo) has the following parameters.

  • dateTimeOffset - The date and time to convert.
  • destinationTimeZone - The time zone to convert dateTime to.

Returns

TimeZoneInfo.ConvertTime(DateTimeOffset, TimeZoneInfo) method returns The date and time in the destination time zone.

Example


// w  ww . j a  va2 s. 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 »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version