0

I have a simple countdown and I would like for there to always be 2 numbers for days, hours, minutes and seconds. For instance, if there's 1 day left, I want it to say 01 instead of 1. How can I modify this code for that?

var countDownDate = new Date('Dec 23, 2019 12:00:00').getTime();
 var x = setInterval(function() {
   var now = new Date().getTime();
   var distance = countDownDate - now;
   var days = Math.floor(distance / (1000 * 60 * 60 * 24));
   var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
   var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
   var seconds = Math.floor((distance % (1000 * 60)) / 1000);
   $('.countdown').html('<div>' + days + '<span>days</span></div> : <div>' + hours + '<span>hrs</span></div> : <div>'
   + minutes + '<span>min</span></div> : <div>' + seconds + '<span>sec</span></div>');
   if (distance < 0) {
  clearInterval(x);
  $('.countdown').hide();
   }
 }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="countdown"></diV>
user13286
  • 2,527
  • 6
  • 34
  • 70
  • 1
    You could make it a string and use [`padStart()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart), e.g. `seconds.toString().padStart(2,'0')`. – Tyler Roper Dec 19 '19 at 19:13
  • Could always add the numbers to a "0" string, and then take the 2 right letters – alamoot Dec 19 '19 at 19:14
  • The issue is I don't want to pad all numbers, there should only be a leading `0` in the event that there's a single digit for days, hours, minutes or seconds. – user13286 Dec 19 '19 at 19:15
  • Node that "number" and "digit" are two words with different meanings. "01" is *one* number having *two* digits. – trincot Dec 19 '19 at 19:15
  • 1
    @user13286 That's exactly what `padStart()` does. It only pads the number if it doesn't meet the length specified by the first argument. For example, `"20".padStart(2,"0")` will still output `"20"`. – Tyler Roper Dec 19 '19 at 19:16
  • @TylerRoper perfect, thank you! – user13286 Dec 19 '19 at 19:16

0 Answers0