Display real timing in webpage


To display real time in webpage that is updated with every second.
 - We use JS for this
 - We can use Date() function to get current date time and
 - Then dynamically update time part in DOM of webpage to display
- This step need to repeated every second to update current time in webpage
- We use JS  function  setTimeout()

-  we can also show countdown timline in webpage

HTML
<body onload="displayTime()">
<div id = "timelement"></div>
<div> deadline: [future date]: <span  id = "deadline">2017-02-02 11:20:23 </span></div>
<div id = "countdown"></div>
</body>



JS
function displayTime() {
   
       // generate current time
      var today = new Date();
      var h = today.getHours();
      var m = today.getMinutes();
      var s = today.getSeconds();

     h  = paddingTime(h);
     m = paddingTime(m);
     s = paddingTime(s);

      // we formate how to show time
      showtime =  h+ " : " + m +" : "+ s ;

      // display current time in HTML DOM
     element = document.getElementById("timelement");
     element.innerHTML = showtime;


        // we can also show countdown timline in webpage
         seldate =  document.getElementById("deadline").innerHTML;
         seldate = new Date(seldate);
         diff = dmsec = seldate - today;

     if(diff>0){
                dday = Math.floor(dmsec/1000/60/60/24);
                dmsec = dmsec - dday*1000*60*60*24;
                dh = Math.floor(dmsec/1000/60/60);
                dmsec = dmsec - dh*60*60*1000;
                dm = Math.floor(dmsec/1000/60);
                dmsec = dmsec - dm*1000*60;
                ds = Math.floor(dmsec/1000);
                dmsec = dmsec - ds;

              countdown = dday + " Days "+ dh + ":" + dm + ":" + ds;
               document.getElementById("countdown").innerHTML = countdown;
       }

     // we call timeout function to repeat every half second  {1sec = 1000 ms}
     setTimeout(function(){ displayTime() }, 500);
}

/* Function to add padding with 0 to make 2 digit number
 *  param int timevalue [0-59]
 * return int  2 digit     [00-09]
 */
function paddingTime(i) {
                if (i < 10) {i = "0" + i};
                return i;
}


Share this

Related Posts

Previous
Next Post »