0

Good morning, Does anyone know how to amend this countdown code so that it always outputs at double digits, i.e. 01 01 01, rather than 1 1 1

<script>
$(document).ready(function () {
setInterval(function () {
var now = new Date();
var day = now.getDay();
var end;

if(day >= 1 && day <= 5) {
end = new Date(now.getYear(), now.getMonth(), day, 14, 0, 0, 0);    
} else {
end = new Date(now.getYear(), now.getMonth(), day, 13, 0, 0, 0);
}

var timeleft = end.getTime() - now.getTime();
ar diff = new Date(timeleft);

$("#countdownTimer").html(diff.getHours() + "&nbsp;" + diff.getMinutes() + "&nbsp;" +     diff.getSeconds());

}, 1000);

});

</script>

Thank you guys

dmt
  • 191
  • 2
  • 21
  • possible duplicate of [How can I create a Zerofilled value using JavaScript?](http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript) – laaposto Jan 08 '15 at 12:09

2 Answers2

1

You can use a date library, or a simple padding function like this:

function padNumber(num, size){
   var s = "0000000000" + num;
   return s.substr(s.length - size);
}

So for your code:

$("#countdownTimer").html(padNumber(diff.getHours(), 2) + "&nbsp;" 
        + padNumber(diff.getMinutes(), 2) + "&nbsp;" 
        + padNumber(diff.getSeconds(), 2));

Note: This simple function does not check the length of the num itself, so specifying too small a size will truncate it (but you get the idea).

While not bullet proof, this is faster than the 3 best options on the link provided here: How can I pad a value with leading zeros?

jsPerf: http://jsperf.com/left-zero-pad/14

Or if you want even simpler and faster (but only for 2 digits)

function pad2(num){
    if(num < 10){
        return "0" + num;
    }
    return "" + num;
}

Note: This last version is soooo fast it leaves the other options for dead (something like 20 times faster).

Community
  • 1
  • 1
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • @dmt: Kind of you to say. For your specific 2-digit usage, go with the last version. It is at least 20 times faster than anything else I have tried. – iCollect.it Ltd Jan 08 '15 at 12:25
0

this simple function should do the trick.

function makeTwoDigit(num)
{
          num = num.toString();
          if(num.length==1)
            return "0"+num;
          return num;
};



setInterval(function () {
          var now = new Date();
          var day = now.getDay();
          var end;
          if(day >= 1 && day <= 5) {
            end = new Date(now.getYear(), now.getMonth(), day, 14, 0, 0, 0);    
          } else {
            end = new Date(now.getYear(), now.getMonth(), day, 13, 0, 0, 0);
          }
          var timeleft = end.getTime() - now.getTime();
          var diff = new Date(timeleft);
          console.log(makeTwoDigit(diff.getHours()) + " " + makeTwoDigit(diff.getMinutes()) + " " +     makeTwoDigit(diff.getSeconds()));
        }, 1000);
shifu
  • 6,586
  • 5
  • 21
  • 21