Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

404
Visualizações
Is there an easier more efficient way I can manipulate the contents of the paragraph tag below?

So I have a timer variable that points to a paragraph in html. Now I want to change the contents of this paragraph to display time

timer.innerHTML = hr + ":" + min;

Note: hr and min are variables that store the current time.

So, in order to avoid a situation where the time shows as "9:7" when it's 09:07am, I added a bunch of if statements

If(hr < 10){
    timer.innerHTML = "0" + hr + ":" + min;
} 
If (min < 10){
    timer.innerHTML = hr + ":" + min;
}

However, I want to do so for hours, minutes, and seconds aswell. Is there a more efficient way to do this rather than with a bunch of if statements. Because it might become quite tedious to write if statements for every possiblity.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try this, with a ternary conditional operator (see the docs on MDN for help):

time.innerHTML = (hr < 10 ? '0' : '') + hr + ':' + (min < 10 ? '0' : '') + min;

Here's the MDN documentation for the conditional operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

about 4 years ago · Juan Pablo Isaza Relatório

0

Use String.prototype.padStart() to pad a string with another string, in this case '0' until it reaches the desired length, which is 2 in this case. (1)

function printTime(hour, minute) {
  const hr = hour.padStart(2, 0)
  const min = minute.padStart(2,0)
  console.log('The time is ' + hr + ':' + min)
}

printTime('12', '45')
printTime('1', '4')
printTime('5', '12')

Since it's a string prototype function, the input either needs to be a string or converted into one. So if you want to use numbers there are a couple of ways you can do it:

function printTime(hour, minute, second) {
  const hr = ('' + hour).padStart(2, 0) // Convert to string in an expression
  
  const minString = minute + '' // Convert and store in a variable
  const min = minString.padStart(2,0)
  
  const sec = second.toString().padStart(2,0) // Use toString()
  
  console.log(`The time is ${hr}:${min}:${sec}`)
}

printTime(12, 45, 2)
printTime(1, 2, 5)
printTime(5, 20 ,59)

I know you didn't ask, but if you look at the console log above, I used template literals to make the final string. They let you interpolate strings with variables and expressions in a cleaner, easier to write, and sexier way. (2)

about 4 years ago · Juan Pablo Isaza Relatório

0

a fun way to do it, using intl api :

const myDateFormat = new Intl.DateTimeFormat( undefined, {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12:false
}) ;

const hr = 8, min = 9, sec = 7 ;

console.log( myDateFormat.format( new Date(0,0,0, hr, min, sec ) ) ) ;

08:09:07

edit > some links around intl :

https://devhints.io/wip/intl-datetime

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/

https://firefox-source-docs.mozilla.org/intl/dataintl.html

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda