Translate

Wednesday, 29 November 2017

JavaScript Timer function clock for 12 hour

Key Note:
Design a page with body onload event

<body onload="startTime()">
<div id="divHeader">
<div style="text-align:right;">Current Time:<label id="lblTime"></label></div>
</div>
</body>


JavaScript:

 <script type="text/javascript">
         function startTime() {
             var today = new Date();           
             var h = today.getHours();
             var m = today.getMinutes();
             var s = today.getSeconds();           
             var ampm = h >= 12 ? 'PM' : 'AM';
             h = h % 12;
             h = h ? h : 12; // the hour '0' should be '12'
             m = m < 10 ? '0' + m : m;            
             s = checkTime(s);
             var strTime = h + ':' + m +':'+s+ ' ' + ampm;            
             document.getElementById('lblTime').innerHTML = strTime;
             var t = setTimeout(startTime, 500);
         }
         function checkTime(i) {
             if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
             return i;
         }         

</script>


Details Code:

<!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>
    <title></title>
     <script type="text/javascript">
         function startTime() {
             var today = new Date();           
             var h = today.getHours();
             var m = today.getMinutes();
             var s = today.getSeconds();           
             var ampm = h >= 12 ? 'PM' : 'AM';
             h = h % 12;
             h = h ? h : 12; // the hour '0' should be '12'
             m = m < 10 ? '0' + m : m;            
             s = checkTime(s);
             var strTime = h + ':' + m +':'+s+ ' ' + ampm;            
             document.getElementById('lblTime').innerHTML = strTime;
             var t = setTimeout(startTime, 500);
         }
         function checkTime(i) {
             if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
             return i;
         }         
</script>
</head>
<body onload="startTime()">
<div id="divHeader">
<div style="text-align:right;">Current Time:<label id="lblTime"></label></div>
</div>

<div id="divBody">
<p>Wel Come</p>
</div>
<div id="divFooter">
<p> Copyright 1999-2017</p>
</div>
</body>

</html>

No comments:

Post a Comment