Does not concatenate the If

Asked

Viewed 60 times

0

Guys, can you help me... I’m learning to make a clock with Javascript...

But if to concatenate 0 in front of seconds, minutes and hours is not working... I can’t find the error...

    var tempo=new Date();
    var hora=tempo.getHours();
    var min=tempo.getMinutes();
    var seg=tempo.getSeconds();

    var impressao=hora + ":" + min + ":" + seg;

    if(hora<10){
        hora="0" + tempo.getHours;
    }
    if(min<10){
        min="0" + tempo.getMinutes;
    }
    if (seg<10){
        seg="0" + tempo.getSeconds;
    }

    document.write(impressao);

3 answers

1


various errors. Put the arrow line printing before write and use () after getHours etc.So:

var tempo=new Date();
var hora=tempo.getHours();
var min=tempo.getMinutes();
var seg=tempo.getSeconds();

if(hora<10){
    hora="0" + tempo.getHours();
}
if(min<10){
    min="0" + tempo.getMinutes();
}
if (seg<10){
    seg="0" + tempo.getSeconds();
}

var impressao=hora + ":" + min + ":" + seg;

document.write(impressao);

but I can make it much better. But I’ll let you figure out how ;)

  • 1

    thank you very much Nelson, helped me a lot!

0

You’re declaring the print variable before the if’s, so it’s taking the values without the zeroes in front. Place the statement after the if’s and print.

0

You already have an accepted answer, but here is another, in my view cleaner and more DRY.

I usually use a simple function for this:

function pad(s) {
    return (s < 10) ? '0' + s : s;
}

That way you don’t repeat code, it gets more organized.

Another tip to organize is to do [hora, min, seg].join(':'); in time of hora + ":" + min + ":" + seg;. Cleaner and uses less measurement since concatenating strings generates a copy of each substring that is concatenated. Note that this line var impressao = ... it has to be after you add the 0, for him to be included in that line, otherwise as you have now he ignores those last lines.

So your code could look like this:

function pad(s) {
    return (s < 10) ? '0' + s : s;
}

var tempo = new Date();
var hora = tempo.getHours();
var min = tempo.getMinutes();
var seg = tempo.getSeconds();

var impressao = [hora, min, seg].map(pad).join(':');
document.body.innerHTML = impressao;

jsFiddle: https://jsfiddle.net/dsq4w29m/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.