C# TimeZoneInfo ConvertTime(DateTime, TimeZoneInfo)

Description

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

Syntax

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


public static DateTime ConvertTime(
  DateTime dateTime,
  TimeZoneInfo destinationTimeZone
)

Parameters

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

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

Returns

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

Example

The following example converts an array of date and time values to times in the Eastern Time zone of the U.S. and Canada. It shows that the source time zone depends on the DateTime.Kind property of the source DateTime value.


/*  w w w  .j  a v a 2 s.  c  o  m*/
using System;

public class Example
{
   public static void Main()
   {
      // Define times to be converted.
      DateTime[] times = { new DateTime(2014, 1, 1, 0, 1, 0), 
                           new DateTime(2014, 1, 1, 0, 1, 0, DateTimeKind.Utc), 
                           new DateTime(2014, 1, 1, 0, 1, 0, DateTimeKind.Local),                            
                           new DateTime(2014, 11, 6, 23, 30, 0),
                           new DateTime(2014, 11, 7, 2, 30, 0) };

      // Retrieve the time zone for Eastern Standard Time (U.S. and Canada).
      TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
  
      Console.WriteLine("Local time zone: {0}\n", TimeZoneInfo.Local.DisplayName);

      // Convert each time in the array. 
      foreach (DateTime timeToConvert in times)
      {
         DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
         Console.WriteLine("Converted {0} {1} to {2}.", timeToConvert, 
                           timeToConvert.Kind, 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