blog

Home / DeveloperSection / Blogs / TimeZone Class in C#

TimeZone Class in C#

Vijay Shukla6272 12-Jun-2013

In this blog I am trying to explain the concept of TimeZone Class in C#.

TimeZone

A time zone is a geographical region in which the same standard time is used. You can use the TimeZone class to get information about the current time zone, and to convert times from local time to Coordinated Universal Time (UTC) or vice versa. However, you cannot use the TimeZone class to represent time zones other than the local zone or to handle date and time conversions from one time zone to another. For this purpose, use the TimeZoneInfo class. You can use this class to retrieve information on any time zone defined on the local system, to create custom time zones, and to convert times from one time zone to another.

Syntax: -

[SerializableAttribute] 
[ComVisibleAttribute(true)]
public abstract class TimeZone
TimeZone Example: -
You need the System.Globalization namespace for use the time zone
classes.
 class TimeZoneDemo
 {
 static void Main()
 {
 Console.WriteLine("{0,-30}{1}", "Standard time name:",
   TimeZone.CurrentTimeZone.StandardName);
 Console.WriteLine("{0,-30}{1}", "Daylight saving time name:",
    TimeZone.CurrentTimeZone.DaylightName);
 Console.WriteLine("\n" + "{0,-30}{1:MM-dd-yyyy HH:mm}", "Current date and time:",    DateTime.Now);
 Console.WriteLine("{0,-30}{1}", "Daylight saving time?",
   TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now));
 DateTime currentUTC =TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now);
 TimeSpan currentOffset =TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
 Console.WriteLine("{0,-30}{1:MM-dd-yyyy HH:mm}", "Coordinated Universal Time:",
   currentUTC);
 Console.WriteLine("{0,-30}{1}", "UTC offset:", currentOffset);
 DaylightTime daylight =
   TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year);
 Console.WriteLine("\nDaylight saving time for year {0}:", DateTime.Now.Year);
 Console.WriteLine("{0:MM-dd-yyyy HH:mm} to " +"{1:MM-dd-yyyy HH:mm}, delta: {2}",    daylight.Start, daylight.End, daylight.Delta);
 Console.ReadKey();
 }
 }

Code description: -
1.       Create a TimeZone class.
2.       Start Main method.
5.       Display the names for standard time and daylight saving.
6.       Time for the local time zone.
7.       Display the current date and time and show if they occur.
8.       Display the current date and time in daylight saving time.
9.       Get the current Coordinated Universal Time (UTC) and UTC.
10.   Get the current Coordinated Universal Time (UTC) and UTC offset.
11.   Show the current Coordinated Universal Time.
12.   Show the Coordinated Universal Time offset.
13.   Get the DaylightTime object for the current year.
14.   Display the daylight saving time range for the current year.
Output: -

TimeZone Class in C#

Updated 18-Sep-2014

Leave Comment

Comments

Liked By