Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Convert Time With Different TimeZones in ASP.NET

Posted by Viral Sarvaiya on October 22, 2010

Here i demostrate how to convert date time with different time zone.

for that make a simple web application having 1 dropdown for select time zone and 2 label for local time and converted time.

in default.aspx page

<table>
 <tr>
 <td>
 <asp:DropDownList ID="ddlZone" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlZone_SelectedIndexChanged"
 AppendDataBoundItems="true">
 <asp:ListItem Text="Select a TimeZone" Value="Default value" />
 </asp:DropDownList>
 </td>
 </tr>
 <tr>
 <td>
 Local Time: <asp:Label ID="lblLocalTime" runat="server" Text=""></asp:Label>
 </td>
 </tr>
 <tr>
 <td>
 Converted Time: <asp:Label ID="lblTimeZone" runat="server" Text=""></asp:Label>
 </td>
 </tr>
 </table>

and in default.aspx.cs file

add namespance “using System.Collections.ObjectModel” for readonlycollection<T>

protected void Page_Load(object sender, EventArgs e)
 {
 if (!Page.IsPostBack)
 {
 lblLocalTime.Text = DateTime.Now.ToString();
 ReadOnlyCollection<TimeZoneInfo> tz;
 tz = TimeZoneInfo.GetSystemTimeZones();
 foreach (TimeZoneInfo timeZone in tz)
 {
 ddlZone.Items.Add(new ListItem(timeZone.DisplayName, timeZone.Id));
 }
 }
 }

 protected void ddlZone_SelectedIndexChanged(object sender, EventArgs e)
 {
 if (ddlZone.SelectedIndex > 0)
 {
 DateTime dt = DateTime.Now;
 lblTimeZone.Text = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
 TimeZoneInfo.Local.Id, ddlZone.SelectedValue).ToString();
 }
 }

now press F5 and run the code….

enjoy coding…..

Advertisements

One Response to “Convert Time With Different TimeZones in ASP.NET”

  1. nice blog viral.. Keep it up…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: