Work With Time And Time Zone in Asp.net

Step 1> add a website and put a aspx page and add a dropdownlist and a label

Step 2> Create a function to bind dropdonlist with time zones and call this function to page load

    >>   Add some namespace as given

using System.Collections.ObjectModel;
using System.Data;



public void bindzone()
    {
        ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
        Console.WriteLine("All time zones:");
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Id");
        dt.Rows.Add("Select Time Zone", "Select Time Zone");
        foreach (TimeZoneInfo timeZoneInfo in timeZones)
        {
            //Console.WriteLine("   {0}", timeZoneInfo.DisplayName);
           // ListBox1.Items.Add(timeZoneInfo.DisplayName.ToString());

            dt.Rows.Add(timeZoneInfo.DisplayName.ToString(), timeZoneInfo.Id.ToString());
        }
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Id";
        DropDownList1.DataSource = dt;
        DropDownList1.DataBind();
    }

call it to pageload

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindzone();
        }
       
    }

Step 3> True autopostback of dropdownlist

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
            Font-Bold="True" ForeColor="Maroon" Height="29px" 
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        </asp:DropDownList>


Step 4> Create another function to display the result

 public void convertdatetime(string timezone)
    {
        DateTimeOffset nowDateTime = DateTimeOffset.Now;
        DateTimeOffset newDateTime = TimeZoneInfo.ConvertTime(nowDateTime, TimeZoneInfo.FindSystemTimeZoneById(timezone.ToString()));
       
        Label1.Text = " Time Is : " + newDateTime.ToString();
    }

Step 5> go to dropdownlist event +double click on selectedindexchange and write this code..

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedItem.ToString() != "Select Time Zone")
            convertdatetime(DropDownList1.SelectedValue.ToString());
        else
            Label1.Text = "Please Select A valid Time Zone!!!";
    }

Now Run the site and check it.

For More help download the code in zip
Ebook Download
View all
Learn
View all