In this article I
am going to explain how to get date and time from timezone in asp.net
Implementation:
Implementation:
HTML Markup:
<fieldset style="width:50%">
<legend><strong>Get data
and time from Timezone</strong> </legend>
<table>
<tr><td>Select
Timezone :</td><td><asp:DropDownList ID="ddltimezone"
runat="server"
AutoPostBack="true">
</asp:DropDownList></td></tr>
<tr><td></td><td></td></tr>
<tr><td colspan="2"><asp:Label ID="lbloutput"
runat="server"
Font-Bold="true"></asp:Label></td></tr>
<tr><td colspan="2"><asp:Label ID="lbldatetime"
runat="server"
Font-Bold="true"></asp:Label></td></tr>
</table>
</fieldset>
Bind Time zone to Dropdownlist
Create a method
to bind the system Timezones to dropdownlist and call it on page load.
C# code:
protected void Page_Load(object
sender, EventArgs e)
{
if (!IsPostBack)
{
BindTimezone();
}
}
public void BindTimezone()
{
try
{
ddltimezone.DataSource = TimeZoneInfo.GetSystemTimeZones();
ddltimezone.DataTextField = "DisplayName";
ddltimezone.DataValueField = "Id";
ddltimezone.DataBind();
ddltimezone.Items.Insert(0,new ListItem("--Select Timezone--"));
}
catch (Exception ex)
{
}
}
VB.net code
Protected Sub Page_Load(sender As
Object, e As
System.EventArgs) Handles
Me.Load
If Not IsPostBack Then
BindTimezone()
End If
End Sub
Public Sub BindTimezone()
Try
ddltimezone.DataSource = TimeZoneInfo.GetSystemTimeZones()
ddltimezone.DataTextField = "DisplayName"
ddltimezone.DataValueField = "Id"
ddltimezone.DataBind()
ddltimezone.Items.Insert(0, New ListItem("--Select Timezone--"))
Catch
ex As Exception
End Try
End Sub
SelectIndex event of Dropdownlist
Write the below
given code on Dropdownlist SelectIndex event.
C# code:
protected void ddltimezone_SelectedIndexChanged(object sender, EventArgs
e)
{
try
{
DateTime
dt = DateTime.Now;
string
timezone = ddltimezone.SelectedItem.Text;
string
datetime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
TimeZoneInfo.Local.Id, ddltimezone.SelectedValue).ToString();
lbloutput.Text = timezone;
lbldatetime.Text = datetime;
}
catch (Exception ex)
{
}
}
VB.net code
Protected Sub ddltimezone_SelectedIndexChanged1(sender As Object, e As System.EventArgs)
Handles ddltimezone.SelectedIndexChanged
Try
Dim
dt As DateTime
= DateTime.Now
Dim
timezone As String
= ddltimezone.SelectedItem.Text
Dim
datetime__1 As String
= TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
TimeZoneInfo.Local.Id,
ddltimezone.SelectedValue).ToString()
lbloutput.Text = timezone
lbldatetime.Text = datetime__1
Catch
ex As Exception
End Try
End Sub
0 Comments