Question

Can somebody help me adding a leading zero do my countdown JavaScript. Tried like 3 hours and now i getting crazy... Here is the clean countdown without any wierd codings I did:

<script type="text/javascript">

var strTargetDate = "05/16/2014 12:00 AM";
var strFormat = "$DAYS$ $HOURS$ $MINUTES$ $SECONDS$";
var strExpired = "DONE";

function doCountDown(seconds)
{
   if (seconds < 0)
   {
      document.getElementById("countdown").innerHTML = strExpired;
      return;
   }
   var strMsg = strFormat;
   strMsg = strMsg.replace("$DAYS$",    ((Math.floor(seconds/86400))%100000).toString());
   strMsg = strMsg.replace("$HOURS$",   ((Math.floor(seconds/3600))%24).toString());
   strMsg = strMsg.replace("$MINUTES$", ((Math.floor(seconds/60))%60).toString());
   strMsg = strMsg.replace("$SECONDS$",  ((Math.floor(seconds))%60).toString());

   document.getElementById("countdown").innerHTML = strMsg;

   setTimeout("doCountDown(" + (seconds-1).toString() + ")", 1000);
}

function initCountDown()
{
   var dtTarget = new Date(strTargetDate);
   var dtNow = new Date();
   var dtDiff = new Date(dtTarget-dtNow);
   var totalSeconds = Math.floor(dtDiff.valueOf()/1000);

   doCountDown(totalSeconds);
}

initCountDown();

</script>
Was it helpful?

Solution

It's a simple matter of detecting if the value is too small and, if it is, prefix it yourself.

Something like replacing:

strMsg = strMsg.replace("$SECONDS$",  ((Math.floor(seconds))%60).toString());

with:

var secs_str = ((Math.floor(seconds)) % 60).toString();
if (secs_str.length < 2) {
    strMsg = strMsg.replace("$SECONDS$", "0" + secs_str);
} else {
    strMsg = strMsg.replace("$SECONDS$", secs_str);
}

Note I haven't tested that code but you should get the basic idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top