TimeZoneInfo Class represents any time zone in
the world. Instance of TimeZoneInfo class is immutable, i.e., when we
instantiate it the value can't be modified.
We can't create an object of TimeZoneInfo class with a new keyword. If you have
ever noticed, this is sealed class and also restricts the inheritance feature.
We can call static member of TimeZoneInfo class.
Difference in TimeZoneInfo Class and TimeZone Class
- By TimeZone we mean a geographical region
in which the same time is used, whereas TimeZoneInfo represents any time
zone.
- The TimeZone knows only local time zone.
This class can only convert the time between UTC (Coordinated Universal
Time) and local time. On the other hand, TimeZoneInfo class can convert time
from one Time Zone to any other Time Zone.
Example
Now, let's understand above concept with the help of one demo. In our demo, we
will perform the following operations:
- Retrieve all Time Zones and display it.
- Get current date and time information
from specified Time Zone Id.
Step 1: Get all available Time Zones
from our registry.
private
static IEnumerable<string>
GetRegistryTimeZoneIds()
{
var timeZones =
TimeZoneInfo.GetSystemTimeZones();
return
timeZones.Select(timeZone => timeZone.Id).ToList();
}
Step 2: From all Time Zones info we get the current date and time
information with the help of a specified Time Zone Id.
private
static void
DisplayRegistryTimeZone()
{
var timeZones =
GetRegistryTimeZoneIds();// Get
all time zone;
foreach
(var zoneId in timeZones)
{
//Get
current date and time information from the specified TimeZone
var localtime =
DateTime.Now;
var timeZoneInfo =
TimeZoneInfo.FindSystemTimeZoneById(zoneId);
var dataTimeByZoneId = TimeZoneInfo.ConvertTime(localtime,TimeZoneInfo.Local,
timeZoneInfo);
Console.WriteLine("Zone
: " + zoneId + " DateTime : " +
dataTimeByZoneId);
}
Console.ReadLine();
}
Output