Javascript: Live countdown to date end (With leading zero for number less than 10)


<script>
    CountDownTimer('05/05/2016 05:04 PM');

    function CountDownTimer(dt)
    {
     var end = new Date(dt);

     var _second = 1000;
     var _minute = _second * 60;
     var _hour = _minute * 60;
     var _day = _hour * 24;
     var timer;

     function showRemaining() {
      var now = new Date();
      var distance = end - now;
      
      var days = Math.floor(distance / _day);
      var hours = Math.floor((distance % _day) / _hour);
      var minutes = Math.floor((distance % _hour) / _minute);
      var seconds = Math.floor((distance % _minute) / _second);
      
      if (distance < 0) {

       clearInterval(timer);
       days = '00';
       hours = '00';
       minutes = '00';
       seconds = '00'; 
      }
      
      document.getElementById('countdown_days').innerHTML = addZero(days);
      document.getElementById('countdown_hrs').innerHTML = addZero(hours);
      document.getElementById('countdown_mins').innerHTML = addZero(minutes);
      document.getElementById('countdown_secs').innerHTML = addZero(seconds);
      
     }

     timer = setInterval(showRemaining, 1000);
    }
    
    function addZero(number) {
      if (number<10) { number = ('0'+number).slice(-2); }
      return number;
    }

   </script>


POSTED BY juong

Popular Posts

.

Back to Top