Using Timer

1.Aspx code

  <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField ID="FinishTime" runat="server" />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
       
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
                </asp:Timer>
                <asp:Label ID="labTimes" runat="server" Width="155px"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
   
    </div>
    </form>
</body>
</html>

2.CS Code

 

 public partial class DemoTimer : System.Web.UI.Page
    {
        private double TotalTime = 0.01;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.FinishTime.Value = DateTime.Now.AddHours(TotalTime).ToString("yyyy/MM/dd HH:mm:ss");
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            DateTime finishTime = DateTime.Parse(this.FinishTime.Value);
            if (DateTime.Now >= finishTime) //如果设置的时间已过
            {
                this.Timer1.Enabled = false;    //将Timmer置为false
                this.labTimes.Text = "时间到!";
            }
            else
            {
                RefreshTime(); //刷新时间
            }

        }
        private void RefreshTime() //刷新时间的方法
        {
            TimeSpan ts = DateTime.Parse(this.FinishTime.Value) - DateTime.Now; //时间差           
            this.labTimes.Text = ts.Hours.ToString().PadLeft(2, '0') + ":" + ts.Minutes.ToString().PadLeft(2, '0') + ":" + ts.Seconds.ToString().PadLeft(2, '0');
        }

    }

 

posted @ 2010-07-20 14:54  C.fly  阅读(169)  评论(0编辑  收藏  举报