Convert Time in Different TimeZones in ASP.NET

Posted by: Suprotim Agarwal , on 10/20/2010, in Category ASP.NET
Views: 132833
Abstract: In this article, we will see how to convert time from one time zone to another, in an ASP.NET application.
In this article, we will see how to convert time from one time zone to another, in an ASP.NET application.
Step 1: Fire up Visual Studio > File > New Website. Drag and drop a DropDownList and two Label controls to the page and add a ‘SelectedIndexChanged’ event to the DropDownList (we will code this event later). The DropDownList will display the different Timezones and the Label controls will display the Local time as well as the Converted time. Here’s how the markup would look like.

 

<form id="form1" runat="server">
<div>
    <asp:DropDownList ID="ddlTimeZone" runat="server" AutoPostBack="True"
        onselectedindexchanged="ddlTimeZone_SelectedIndexChanged"
        AppendDataBoundItems="true" >
            <asp:ListItem Text="Select a TimeZone" Value="Default value" />
    </asp:DropDownList>
    <br /><br />   
    Local Time: <asp:Label ID="lblLocalTime" runat="server" Text=""></asp:Label>
    <br /><br />
    Converted Time: <asp:Label ID="lblTimeZone" runat="server" Text=""></asp:Label>           
</div>
</form>
 
Step 2: We will now populate the DropDownList with the different TimeZones available. A simple way to do that is to use the TimeZoneInfo.GetSystemTimeZones method. This method returns a generic ReadOnlyCollection(Of T) collection of TimeZoneInfo objects.
Write the following code in the Page_Load method
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        lblLocalTime.Text = DateTime.Now.ToString();
        ReadOnlyCollection<TimeZoneInfo> tzi;
        tzi = TimeZoneInfo.GetSystemTimeZones();        
        foreach (TimeZoneInfo timeZone in tzi)
        {
            ddlTimeZone.Items.Add(new ListItem(timeZone.DisplayName, timeZone.Id));               
        }
    }
}
 
VB.NET (Converted Code)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      If Not Page.IsPostBack Then
            lblLocalTime.Text = Date.Now.ToString()
            Dim tzi As ReadOnlyCollection(Of TimeZoneInfo)
            tzi = TimeZoneInfo.GetSystemTimeZones()
            For Each timeZone As TimeZoneInfo In tzi
                  ddlTimeZone.Items.Add(New ListItem(timeZone.DisplayName, timeZone.Id))
            Next timeZone
      End If
End Sub
As you can see, we first extract the different TimeZones available on the machine using TimeZoneInfo.GetSystemTimeZones and then loop through the collection and add the name and value to the DropDownList. The TimeZoneInfo.DisplayName is the Name and the TimeZoneInfo.Id is the value added to the DropDownList.
image_2
Step 3: The last step is to convert the local time into the TimeZone selected by the user in the DropDownList. We will do the conversion using the TimeZoneInfo.ConvertTimeBySystemTimeZoneId. This method converts a time from one time zone to another based on the ‘time zone identifier’ without the need to know whether the converted time is standard or daylight saving time. Remember we used the TimeZoneInfo.Id that formed the ‘value’ of the DropDownList in Step 2. We will use that value here as shown below:
C#
protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlTimeZone.SelectedIndex > 0)
    {
        DateTime dt = DateTime.Now;
        lblTimeZone.Text = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
            TimeZoneInfo.Local.Id, ddlTimeZone.SelectedValue).ToString();
    }
}
 
VB.NET (Converted Code)
Protected Sub ddlTimeZone_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
      If ddlTimeZone.SelectedIndex > 0 Then
            Dim dt As Date = Date.Now
            lblTimeZone.Text = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneInfo.Local.Id, ddlTimeZone.SelectedValue).ToString()
      End If
End Sub
That’s it. Run the application and convert the local time into the desired TimeZone as shown below
image_1
The entire source code of this article can be downloaded over here.
I hope you liked the article and I thank you for viewing it. 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by shivshanker7 on Tuesday, December 7, 2010 11:09 PM
Its a nice solution.
I have search this type of code on many site
actually i want to create timezone for nepalese datetime standard
this article really help me and suppose help to others

many thanks to author
Comment posted by Stewy on Monday, December 27, 2010 3:28 PM
  For Each timeZone As TimeZoneInfo In TimeZoneInfo.GetSystemTimeZones()
            ddlTimeZones.Items.Add(New ListItem(timeZone.DisplayName, timeZone.Id))
        Next
Comment posted by Abdul Rauf on Saturday, February 5, 2011 12:43 AM
Thanks for sharing such a nice information.
Comment posted by Ahmed on Saturday, February 5, 2011 12:33 PM
It working fine,thanks for sharing .
Comment posted by Ahmed on Saturday, February 5, 2011 1:00 PM
It working fine,thanks for sharing .
Comment posted by Prasanta on Tuesday, May 15, 2012 6:28 AM
Really Good one.
Comment posted by Jasmin Chauhan on Saturday, August 11, 2012 3:41 AM
Good, BUT, i need to set it global like in file, Global.asax or web.config file, so it works for whole website, if you have the solution then email me.
Comment posted by Yashwanth Sannithi on Saturday, August 11, 2012 5:39 AM
nice article
Comment posted by pradnya on Tuesday, September 11, 2012 7:35 AM
Thanks for sharing knowledge.Thanks a lot.very much useful for me
Comment posted by Akash jagtap on Saturday, November 24, 2012 11:56 PM
Thanks ,Mr.agarwal
Comment posted by WAT on Friday, December 21, 2012 3:47 PM
Does this also handles daylight savings time for each time zone?  Thanks.
Comment posted by WAT on Saturday, December 22, 2012 7:19 AM
Does this also handles daylight savings time for each time zone?  Thanks.
Comment posted by Karthika on Sunday, April 14, 2013 11:08 PM
Thank yu so much it helped me lot :)
Comment posted by Nikita Somaiya on Tuesday, April 30, 2013 2:27 AM
Good Artical !!!!!!!!
Comment posted by Patidar on Saturday, June 29, 2013 12:07 AM
It's Working Fine.I want Exact same things.Thanks a lot
Comment posted by jasmin on Sunday, August 25, 2013 10:44 PM
this can do everybody, do you have any global solution for timezone settings in web.config file
Comment posted by Salman on Thursday, March 27, 2014 11:25 AM
Does this also handles the daylight saving?
Comment posted by ahmed on Monday, May 11, 2015 1:04 PM
very useful