Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Single digit if-statements not working for time (4:22:22 showing instead of 04:22:22)?

I have this simple program that takes a time from the future and creates a countdown until that time:

var x = setInterval(function() {

            // Get today's date and time
            var now = new Date().getTime();
  
            // Find the distance between now and the count down date
            var distance = Number(String(timerOrigin.innerHTML)+"000") - now;
  
            // Time calculations for days, hours, minutes and seconds

            //Days are not displayed, only used to help calculate hours
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));


            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + (days * 24);
            if (hours.length == 1) {
                hours= "0" + hours;
            }


            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            if (minutes.length == 1) {
                minutes= "0" + minutes;
            }


            var seconds = Math.floor((distance % (1000 * 60)) / 1000);

            if (seconds.length == 1) {
                seconds = "0" + seconds;
            }
                
            // Display the time
            timer.innerHTML = hours + ":" + minutes + ":" + seconds;
  
            // If the count down is finished, Display score
            if (distance < 0) {
            clearInterval(x);
            timer.innerHTML = homeTeamScore.innerHTML + "-" + awayTeamScore.innerHTML;
            }
        }, 1000);

//Push to Dom
            sideScore.appendChild(timer)

The issue I'm having is that the single-digit if statements are not working.

var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + (days * 24);
            if (hours.length == 1) {
                hours= "0" + hours;
            }

this will return 4:22:22 whereas the desired result is 04:22:22. I know I'm missing something somewhere but I cannot put my finger on it. I also ran some log tests and the program is not even getting into the if statements. The console returns no errors as well. Perhaps it's an issue with the scoping since this is all inside of a loop? Any help is appreciated.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!