Do not concatenate or If

0

Well, you can 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 not 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);
    
asked by anonymous 05.05.2016 / 00:30

3 answers

1

Multiple errors. Put the line that prints arrow before the write and use () after the 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 you can improve on that a lot. But I'll let you find out how;)

    
05.05.2016 / 01:43
0

You are declaring the print variable before the if's, so it is picking up the values without the leading zeros. Put the statement after the if's and print.

    
05.05.2016 / 00:42
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;
}

This way you do not repeat code, it gets more organized.

Another tip for organizing is to [hora, min, seg].join(':'); instead of hora + ":" + min + ":" + seg; . Cleaner and uses less memory since concatenating strings generates a copy of each substring that is being concatenated. Note that this var impressao = ... line must be after you add 0 , so that it is included in this line, otherwise you have it now it ignores these 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: link

    
05.05.2016 / 03:53