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

213
Visualizações
Formatting Duration in Correct Format `HH:MM`

I have some logic designed to generate a formatted duration based on an inputted start and stop time:

  getFormattedDuration = async (stopValue, startValue) => {
    const durValue = moment(stopValue, "H:mm").diff(moment(startValue, "H:mm"));
    const t = moment.duration(durValue);

    const duration = {
      hours: t.hours(),
      minutes: t.minutes()
    }

    const formattedDuration = `0${duration.hours}:${duration.minutes}`;
    return formattedDuration;

    // I'm prepending a `0` here because I know the duration will never be above a certain limit - i.e. it will never get to a double digit number for hours.

  } 

This works for the most part. But on occasion I will end up with something like this for output:

duration:  Object {
  "hours": 0,
  "minutes": 8,
}

formattedDuration:  00:8

What I want here is 00:08. How can I pad with zeroes, as necessary, to ensure I get a correctly formatted duration value - which should be in this format hh:mm. Does moment.js have a function I can use to handle this?

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

0

You can use the format() function from moment.js.

const m = moment('00:8','HH:mm').format('HH:mm');

console.log(m) // "00:08"

m = moment('00:8','HH:mm').format('HH:mm');

console.log(m)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use to .padStart() to ensure there are leading zeros.

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