I’m going to achieve this using a timer and update panel.
Add the following code into page source.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Clock</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="smClock" runat="server">
</asp:ScriptManager>
<asp:Timer ID="tmrClock" runat="server" Interval="1000" OnTick="tmrClock_Tick">
</asp:Timer>
<asp:UpdatePanel ID="aupTime" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<table>
<tr>
<td>
<asp:Label ID="lblTm" runat="server" Font-Bold="True" Font-Size="XX-Large" Text="CurrentTime ="></asp:Label>
</td>
<td>
<asp:Label ID="lblTime" runat="server" Font-Bold="True" Font-Size="XX-Large"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tmrClock" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>It is important to use an update panel, otherwise the whole page will get refreshed in every second (we are going to change the value of the label once in every 1000 milliseconds.). Make sure to put your timer within the update panel as well.
Add the following to your code file in order to get the system time and format it in the label.
protected void Page_Load(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss");
}
protected void tmrClock_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss");
}
Here I added the code inside the “Page_Load” event as well to make sure to display the time when page loads. Otherwise we have to wait 1 second to see the time.
Then you can see the system time like this,
Here I’m displaying in 24h format. If you want to display in 12h format use ("hh:mm:ss") instead of ("HH:mm:ss").
Good Luck!!!
Happy Programming :)
No comments:
Post a Comment