Importance of TimeZoneInfo class in ASP.NET



I would like you to give your attention to the following problems.

You are working on an ASP.NET application which is hosted in a server in a USA time zone.

You need to send an email to your customers daily at 10 AM in the Singapore time zone. How is that possible?

How to get all the timezones in the current system?

What is the current time zone Id?

The answers for all these questions would be the TimeZoneInfo class.

TimeZoneInfo

The TimeZoneInfo class represents any time zone in the world. It contains a set of static methods/properties that allows us to get the current time zone information, convert datetime values between time zones etc.

timezone1.gif

The important properties or methods are described below:

Name Type Description
Local Static Property Gets the current TimeZoneInfo of machine
GetSystemTimeZones() Static Method Returns the list of world TimeZoneInfo available
ConvertTime() Static Method Converts time in one zone to another
Id Instance Property String identifier of TimeZoneInfo
DisplayName Instance Property Display name in localized text
GetUtcOffset() Instance Method Returns the difference in timezone difference with Universal Time (UTC)

The Test Application

The test application attached provides:
  • Information on Current Time Zone
  • Displays list of TimeZoneInfo available

timezone2.gif

Converting current datetime to another TimeZone


So what about converting the current time to another time zone?

Here is the answer: Use the TimeZoneInfo.ConvertTime() method.

Code Example:

TimeZoneInfo timeZone = TimeZoneInfo.GetSystemTimeZones().Where(t => t.Id == "Central Standard Time").First();

DateTime newTime = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone);

The method ConvertTime() takes the current time and new time zone as arguments.

Up Next
    Ebook Download
    View all
    Learn
    View all