CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Convert DateTime to Different TimeZone in C#, ASP.Net
Submitted By Satheesh Babu B
On 5/5/2011 8:21:43 AM
Tags: ASP.Net ,CodeDigest,DateTime  

Convert DateTime to Different TimeZone in C#, ASP.Net

 

There will be requirements where we need to display or convert the current date and time to a different time zone's data and time. We can do this by using TimeZoneInfo class packed in System.Collections.ObjectModel namespace.

 

The TimeZoneInfo class has method called ConvertTime() which can be used to convert a datetime to a specified time zone's datetime.
TimeZoneInfo.ConvertTime(DateTime dt, TimeZoneInfo t)
dt - DateTime that needs to be converted
t - Target time zone
The above function will return the converted DateTime.

 

The below code will print different time zones present in the server and the current time in each time zone by converting the server's current date time. Please note that this works only in .Netframework 3.5 and above.

 

protected void Page_Load(object sender, EventArgs e)
    {       
        ReadOnlyCollection<TimeZoneInfo> tz = TimeZoneInfo.GetSystemTimeZones();
        foreach (TimeZoneInfo t in tz)
        {
            Response.Write("Time Zone = "+t.DisplayName + " || Current DateTime = " + TimeZoneInfo.ConvertTime(DateTime.Now, t).ToString());
            Response.Write("<br>");           
        }    
    }

 

Include System.Collections.ObjectModel namespace for the above code to work.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..