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

191
Visualizações
Calculate duration using timestamps (string)

Newcomer here to the coding world.

I've written this chunk of code to calculate the time difference (duration) between two timestamps. I'm pretty happy with it. But I want to know if there is any way I can improve on what I wrote and get the same outcome.

Here's an example,


  const startTime = 2202-05-12 + "T" + 10:00:00 + "Z"
  const endTime = 2202-05-12 + "T" + 11:45:00 + "Z"

  const format_startTime = new Date(startTime);
  const format_endTime = new Date(endTime)

  const hours_startTime = format_startTime.getHours()
  const hours_endTime = format_endTime.getHours()

  const min_startTime = format_startTime.getMinutes()
  const min_endTime = format_endTime.getMinutes()

  const hours_Duration = hours_endTime - hours_startTime
  const min_Duration = min_endTime - min_startTime

  const min_Decimal = min_Duration * (1/60)

  const duration = hours_Duration + (min_Decimal === 0 ? '' : min_Decimal) + " hours";

Result - 1.75 hours

Edit 1 - to clarify, the requirement for this exercise is to use date and time in string format.

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

0

You can subtract one timestamp directly from the other to get the difference in milliseconds. Your version will also only be accurate if both timestamps are on the same day.

  const startTime = "2202-05-12T10:00:00Z"
  const endTime = "2202-05-12T11:45:00Z"

  const format_startTime = new Date(startTime);
  const format_endTime = new Date(endTime);

  const differenceInMillis = format_endTime - format_startTime;
  const differenceInHours = differenceInMillis / 1000 / 60 / 60; // 1.75
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