Как отформатировать число, чтобы оно всегда было двузначным перед десятичной - PullRequest
0 голосов
/ 14 мая 2018

Я построил часы обратного отсчета, и мне нужны минуты и секунды, чтобы всегда отображать двойные цифры. В настоящее время часы работают отлично, но они показывают только одну цифру, когда секунды и минуты опускаются ниже двухзначного числа. (например, ниже 10.) Есть ли jQuery .format () или что-то подобное для форматирования выходных чисел?

Вот мой JS:

// Set the date we're counting down to
    var countDownDate = new Date("March 27, 2019 00:00:00").getTime();

// Update the count down every 1 second
    var x = setInterval(function() {

// Get todays date and time
    var now = new Date().getTime();

// Find the distance between now an the count down date
    var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
    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);
 // Output the result in an element with id="demo"
     document.getElementById("countdown").innerHTML = '<div class="timer-wrapper"><div class="time">' + days + ':</div><span class="text">DAYS</span></div><div class="timer-wrapper"><div class="time">' + hours + ':</div><span class="text">HOURS</span></div><div class="timer-wrapper"><div class="time">' +
            minutes + ':</div><span class="text">MINUTES</span></div><div class="timer-wrapper"><div class="time">' + seconds + '</div><span class="text">SECONDS</span></div>';

  // If the count down is over, write some text 
     if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
        }
    }, 1000);

и вот мой HTML:

<div class="countdown-timer-wrapper">
     <div class="timer" id="countdown"></div>
</div>

Заранее спасибо. :)

1 Ответ

0 голосов
/ 14 мая 2018

Используйте ("0" + number).slice(-2), чтобы отформатировать число

Попробуйте приведенный ниже фрагмент кода

// Set the date we're counting down to
    var countDownDate = new Date("March 27, 2019 00:00:00").getTime();

// Update the count down every 1 second
    var x = setInterval(function() {

// Get todays date and time
    var now = new Date().getTime();

// Find the distance between now an the count down date
    var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
    var days =  Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours =  ("0" +Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).slice(-2);
    var minutes = ("0" + Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))).slice(-2);
    var seconds =  ("0" + Math.floor((distance % (1000 * 60)) / 1000)).slice(-2);
 // Output the result in an element with id="demo"
     document.getElementById("countdown").innerHTML = '<div class="timer-wrapper"><div class="time">' + days + ':</div><span class="text">DAYS</span></div><div class="timer-wrapper"><div class="time">' + hours + ':</div><span class="text">HOURS</span></div><div class="timer-wrapper"><div class="time">' +
            minutes + ':</div><span class="text">MINUTES</span></div><div class="timer-wrapper"><div class="time">' + seconds + '</div><span class="text">SECONDS</span></div>';

  // If the count down is over, write some text 
     if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
        }
    }, 1000);
<div class="countdown-timer-wrapper">
     <div class="timer" id="countdown"></div>
</div>
...