Getting Date and Time Using TimeZoneInfo in C#

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.
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.
  1. private static IEnumerable<string> GetRegistryTimeZoneIds()  
  2. {  
  3. var timeZones = TimeZoneInfo.GetSystemTimeZones();  
  4. return timeZones.Select(timeZone => timeZone.Id).ToList();  
  5. }
Step 2: From all Time Zones info we get the current date and time information with the help of a specified Time Zone Id. 
  1. private static void DisplayRegistryTimeZone()  
  2. {  
  3. var timeZones = GetRegistryTimeZoneIds();// Get all time zone;  
  4. foreach (var zoneId in timeZones)  
  5. {  
  6. //Get current date and time information from the specified TimeZone  
  7. var localtime = DateTime.Now;  
  8. var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneId);  
  9. var dataTimeByZoneId = TimeZoneInfo.ConvertTime(localtime,TimeZoneInfo.Local, timeZoneInfo);  
  10. Console.WriteLine("Zone : " + zoneId + " DateTime : " + dataTimeByZoneId);  
  11. }  
  12. Console.ReadLine();  
  13. }  



Next Recommended Reading How to shut down your PC using C#