Is there a way to include leading zeroes for single digits in a JavaScript live timer? Currently, my timer displays days, hours, minutes, and seconds but when the value is between 1-9 it only shows a single digit. I want it to display as 01, 02, etc.
For example, instead of displaying just "1" for days, I want it to show "01".
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let event = "July 10, 2021 01:00:00",
countDown = new Date(event).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById("days").innerText = ('0' + Math.floor(distance / (day))).slice(-2),
document.getElementById("hours").innerText = ('0' + Math.floor((distance % (day)) / (hour))).slice(-2),
document.getElementById("minutes").innerText = ('0' + Math.floor((distance % (hour)) / (minute))).slice(-2),
document.getElementById("seconds").innerText = ('0' + Math.floor((distance % (minute)) / second)).slice(-2);
//do something later when date is reached
if (distance < 0) {
let headline = document.getElementById("headline"),
countdown = document.getElementById("countdown"),
content = document.getElementById("content");
countdown.style.display = "none";
content.style.display = "block";
clearInterval(x);
}
//seconds
}, 0)
}());
.container {
color: black;
margin: 0 auto;
text-align: center;
font-family: "Nunito";
}
h1 {
font-weight: normal;
letter-spacing: .125rem;
text-transform: uppercase;
}
li {
display: inline-block;
font-size: 1.5em;
list-style-type: none;
padding: 1em;
}
li span {
display: block;
font-size: 4.5rem;
}
@media all and (max-width: 768px) {
h1 {
font-size: 1.5rem;
}
li {
font-size: 1.125rem;
padding: .85rem;
}
li span {
font-size: 3.375rem;
}
}
<div class="container" style="position: absolute;">
<div id="countdown">
<ul style="margin-top: -30px">
<li><span id="days"></span>days</li>
<li><span id="hours"></span>hours</li>
<li><span id="minutes"></span>mins</li>
<li><span id="seconds"></span>secs</li>
</ul>
<script src="script.js"></script>
</div>