Search This Blog

Tuesday 16 October 2012

Clock on webpage using server and system time?


Default.aspx page
<table>
            <tr>
                <td>
                    Time: <span id="TimeDisplay"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </td>
            </tr>
   </table>

Default.aspx.cs file

 protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = Convert.ToString(DateTime.Now.TimeOfDay);
        Response.Write("<script>var timeServer = new Date('" + DateTime.Now.ToString() + "');</script>");
       

         const string crlf = "\r\n";
        string jsscript = "<script type='text/javascript'>"
            + crlf + "window.onload=startclock;" + crlf + "var clock;" + crlf + "var time_diff;" + crlf +
            "function startclock(){" + crlf + "clock=document.getElementById('TimeDisplay');"
            + crlf + "server_time = new Date('" + WelcomeDetails.Rows[0]["CurrentTime"] + "');" +
            crlf + "time_diff=new Date()-server_time;" + crlf + "setInterval('runclock()',1000);" + crlf + "}"
            + crlf + "function runclock(){" + crlf +
            "var cDate=new Date();" + crlf +
            "cDate.setTime(cDate.getTime()-time_diff);" + crlf +
            "var DateString = cDate.format('dd MMMM yyyy');" + crlf +
            "var tmr ='Time: ';" + crlf +
            "var curr_hours = cDate.getHours();" + crlf +
            "var timeofDay = (curr_hours < 12) ? 'AM' : 'PM';" + crlf +
            "curr_hours = (curr_hours > 12) ? curr_hours - 12 : curr_hours;" + crlf +
            "curr_hours = (curr_hours == 0) ? 12 : curr_hours;" + crlf +
            "var curr_mins = cDate.getMinutes();" + crlf +
            "var curr_secs = cDate.getSeconds();" + crlf +
            "curr_hours=(curr_hours < 10)?'0' + curr_hours:curr_hours;" + crlf +
            "curr_mins=(curr_mins < 10)?'0' + curr_mins:curr_mins;" + crlf +
            "curr_secs=(curr_secs < 10)?'0' + curr_secs:curr_secs;" + crlf +
        "clock.innerHTML=tmr + DateString+', '+curr_hours+':'+curr_mins+':'+curr_secs +' '+timeofDay+' (CST)'" + crlf + "}" +
            crlf + "</script>";

        Page.RegisterStartupScript("ServerTimeScript", jsscript);
     
    }

No comments:

Post a Comment