Kyrbi
Kyrbi

Reputation: 2260

Leading zero if number is lower than 10 - bug with number 0

I'm creating some kind of JS clocks where real life minute == 1 clock's hour. But there is one bug, every number in minutes which is lower than 10 is rewritten to "0"+minute, so it looks like 01, 02 and etc. but there is a problem with number 0, it's output is 0, not 00 as I wanted, here is my code.

// time and date
var minute = 57;
var hour = 0;

function getTime(){
    $("#time").html(hour+":"+minute);
};
function init(){
    setInterval(function(){getTime();}, 1000);
    setInterval(function(){
        if (minute == 59){
            hour=++hour;
            minute=minute-59;           // (\(\    Hoo hoo
        }                               // ( . .)  you found
        else {                          // c(“)(“) a bunny :)
            minute=++minute;
            if (minute < 10){
                minute="0"+minute;
            } 
        } 
    }, 1000);
}
init();

Thanks for any help. :)

Upvotes: 0

Views: 96

Answers (3)

user1864610
user1864610

Reputation:

How about:

 $("#time").html(hour+":"+("00"+minute).slice(-2));

and remove the concatenation where you're incrementing the minute

Upvotes: 1

Elon Than
Elon Than

Reputation: 9775

You are setting minute = 0 in if block, not else.

Just replace minute=minute-59 with minute = '00', because that's only one case when you'll enter that if (minute must be equal to 59 and then you're subtracting 59 from it, so it'll be always 0).

Upvotes: 1

Flash Thunder
Flash Thunder

Reputation: 12045

hour = hour.toString();
minute = minute.toString();
while (hour.length < 2) hour = "0" + hour;
while (minute.length < 2) minute = "0" + minute;

Upvotes: 0

Related Questions