Loading color scheme

How to get a list of all timezones and their UTC Offsets in C# (With Sample Code)

If you are writing an international website, it is better to show timestamps to the users in their local timezone. Not everybody can easily translate time from UTC to their local time. Displaying time in a different timezone is confusing to the users and can lead to many misunderstandings. That's why you may want to give the user a choice to select timezone and then make them happy by displaying all timestamps in their local timezones.

But how do you get the timezones list? Here is a little C# code example that shows how to display UTC offset and user-friendly timezone labels:


using System;
					
public class Program
{
	public static void Main()
	{
		foreach (TimeZoneInfo zone in TimeZoneInfo.GetSystemTimeZones())
		{
			int zoneLen = zone.DisplayName.IndexOf(")");
			string timeZone = zone.DisplayName.Substring(0, zoneLen + 1);
			Console.WriteLine(timeZone + " " + zone.Id);
		}
	}
}

This will give us nicely formatted output:

(UTC-09:00) Alaskan Standard Time
(UTC-09:00) UTC-09
(UTC-08:00) Pacific Standard Time (Mexico)
(UTC-08:00) UTC-08
(UTC-08:00) Pacific Standard Time
(UTC-07:00) US Mountain Standard Time
(UTC-07:00) Mountain Standard Time (Mexico)
(UTC-07:00) Mountain Standard Time
(UTC-06:00) Central America Standard Time
(UTC-06:00) Central Standard Time
(UTC-06:00) Easter Island Standard Time
(UTC-06:00) Central Standard Time (Mexico)
(UTC-06:00) Canada Central Standard Time
(UTC-05:00) SA Pacific Standard Time
(UTC-05:00) Eastern Standard Time (Mexico)
(UTC-05:00) Eastern Standard Time

You can later parse the number in the brackets to get the UTC offset for calculations:

 


            string timezonne = "(UTC-05:00) Eastern Standard Time";

            timezonne = timezonne.Remove(0, timezonne.IndexOf(")") + 2);
            TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById(timezonne);



            DateTime localDateDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeInfo);

 

Get all interesting articles to your inbox
Please wait