JS countdown - How to insert a "zero" in front of numbers smaller than 9?

Asked

Viewed 410 times

0

I found a very simple and functional script to count down, but it has a problem; when the counter reaches 9, it no longer has two characters, something that ends up ruining the alignment I had to do to structure the CSS. Someone knows how to solve by inserting an "0' in front of numbers smaller than 9?

<div class="contador_ajuste_largura">
   <div class="contador" >
      <script type="text/javascript">
         function atualizaContador(YY,MM,DD,HH,MI,saida) {
            var SS = 00;
            var hoje = new Date();
            var futuro = new Date(YY,MM-1,DD,HH,MI,SS);

            var ss = parseInt((futuro - hoje) / 1000);
            var mm = parseInt(ss / 60);
            var hh = parseInt(mm / 60);
            var dd = parseInt(hh / 24);

            ss = ss - (mm * 60);
            mm = mm - (hh * 60);
            hh = hh - (dd * 24);

            var faltam = '';
            faltam += (dd && dd > 1) ? dd+'&nbsp:&nbsp;' : (dd==1 ? '1 dia, ' : '');
            faltam += (toString(hh).length) ? hh+'&nbsp:&nbsp;' : '';
            faltam += (toString(mm).length) ? mm+'&nbsp:&nbsp;' : '';
                faltam += (toString(mm).length) ? ss+'&nbsp' : '';

            if (dd+hh+mm+ss > 0) {
                document.getElementById(saida).innerHTML = faltam;
                setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida)},1000);
            } else {
                document.getElementById(saida).innerHTML = '';
                setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida)},1000);
            }
         }

         window.onload=function(){
            atualizaContador('2017','11','23','23','59','elemento');
         }
      </script>
   </div>
</div>

4 answers

1

Makes a if by checking if the number is less than 9

if (numero <= 9){
  var numero = '0' + numero
}

1


Just check if the number is equal or less than 9, and insert the 0 in front.

let numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

for(let i = 0; i < numeros.length; i++){
  if(numeros[i] <= 9){
    numeros[i] = '0' + numeros[i]
  }
  console.log(numeros[i])
} 

If you want to see this working in your example

function atualizaContador(YY,MM,DD,HH,MI,saida) {
  var SS = 00;
  var hoje = new Date();
  var futuro = new Date(YY,MM-1,DD,HH,MI,SS);

  var ss = parseInt((futuro - hoje) / 1000);
  var mm = parseInt(ss / 60);
  var hh = parseInt(mm / 60);
  var dd = parseInt(hh / 24);

  ss = ss - (mm * 60);
  mm = mm - (hh * 60);
  hh = hh - (dd * 24);
  
  ss = ss <= 9 ? '0' + ss : ss
  mm = mm <= 9 ? '0' + mm : mm
  hh = hh <= 9 ? '0' + hh : hh

  var faltam = '';
  faltam += (dd && dd > 1) ? dd+'&nbsp:&nbsp;' : (dd==1 ? '1 dia, ' : '');
  faltam += (toString(hh).length) ? hh+'&nbsp:&nbsp;' : '';
  faltam += (toString(mm).length) ? mm+'&nbsp:&nbsp;' : '';
  faltam += (toString(mm).length) ? ss+'&nbsp' : '';

  if (dd+hh+mm+ss > 0) {
    document.getElementById(saida).innerHTML = faltam;
    setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida)},1000);
  } else {
    document.getElementById(saida).innerHTML = '';
    setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida)},1000);
  }
}

window.onload=function(){
  atualizaContador('2017','11','23','23','59','contador');
}
<div id="contador"></div>

1

You can do it more cheaply...

Suggestion:

function atualizaContador(futuro, mostrador, callback) {
  var el = document.getElementById(mostrador);

  var contador = setInterval(function() {
    var agora = new Date();
    var diff = futuro - agora;
    if (diff <= 0) {
      callback();
      return clearInterval(contador);
    }
    var ss = diff / 1000;
    var mm = ss / 60;
    var hh = mm / 60;
    var dd = hh / 24;
    var falta = [dd, hh, mm, ss % 60].map(nr => ('0' + Math.floor(nr)).slice(-2));
    el.innerHTML = falta.join(':');

  }, 1000);

}

window.onload = function() {
  var final = new Date(2017, 11, 23, 23, 59);
  atualizaContador(final, 'mostrador', function() {
    alert('É Natal!');
  });
}
<div id="mostrador"></div>

1

A very simple solution is to use the function padStart of String, that guarantees you the size and filling with zeros.

Take the example:

let horas = 2;
let minutos = 8;
let segundos = 9;

let relogio = horas.toString().padStart(2,"0") + ":" + 
              minutos.toString().padStart(2,"0") + ":" + 
              segundos.toString().padStart(2,"0");
              
console.log(relogio);

The function was called with 2 in the first parameter that is the number of paths to display, and with "0" in the second parameter, which is the character to be completed.

In the example you have would be applied to the variable faltam not needing to make the checks ss = ss <= 9 ? '0' + ss : ss that has.

See how it would look in your code:

function atualizaContador(YY,MM,DD,HH,MI,saida) {
  var SS = 00;
  var hoje = new Date();
  var futuro = new Date(YY,MM-1,DD,HH,MI,SS);

  var ss = parseInt((futuro - hoje) / 1000);
  var mm = parseInt(ss / 60);
  var hh = parseInt(mm / 60);
  var dd = parseInt(hh / 24);

  ss = ss - (mm * 60);
  mm = mm - (hh * 60);
  hh = hh - (dd * 24);

  let faltam = (dd && dd > 1) ? dd+'&nbsp:&nbsp;' : (dd==1 ? '1 dia, ' : '') +
            hh.toString().padStart(2,"0") + ":" +
            mm.toString().padStart(2,"0") + ":" + 
            ss.toString().padStart(2,"0");

  if (dd+hh+mm+ss > 0) {
    document.getElementById(saida).innerHTML = faltam;
    setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida)},1000);
  } else {
    document.getElementById(saida).innerHTML = '';
    setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida)},1000);
  }
}

window.onload=function(){
  atualizaContador('2017','11','23','23','59','contador');
}
<div id="contador"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.