Tuesday, March 29, 2011

C# TimeZone Corresponding Time

In an Application (public web site) Development, TimeZone is the key if there is a time dependency for making some actions/transactions and the site is public facing across the Globe in different time zones.

TimeZoneInfo class holds the information of TimeZone properties i.e., TimeZone Display Name, TimeZone ID, All the available TimeZones and the Local TimeZone.

The below code snippet explains the real time implementation to get the TimeZone Corresponding Time.
private DateTime GetBaseDateTime(string sourceTimeZoneName)
  TimeZoneInfo sourceTimeZone = null;
  //loop through all the TimeZones to get source TimeZone object
  foreach (TimeZoneInfo tz in TimeZoneInfo.GetSystemTimeZones())
    if (tz.DisplayName.ToUpper() == sourceTimeZoneName.ToUpper())
      sourceTimeZone = tz;
  //TimeZoneInfo.Local gives the local timezone

  DateTime sourceTime = DateTime.MinValue;
  if (null != sourceTimeZone)
    //get the source datetime based on the source timezone
    sourceTime = TimeZoneInfo.ConvertTime(DateTime.Now, sourceTimeZone);
  return sourceTime;

No comments:

Post a Comment