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

227
Visualizações
Generating Duration from Time Values

I am trying to find a way via moment.js to convert two time values, which are coming in as as start and stop times, expressed in hours and minutes as string values, like this: start: 1:12, and stop: 2:10, or in the afternoon, start: 14:23, and stop: 15:22 and generate a duration in milliseconds from this. I have tried the following, but it gives me a NaN result:

Just to clarify, I am receiving the data in string format. See below for what that looks like:

const startValue = "1:12";
const stopValue = "2:10"; // for a duration of 58 minutes

const msDuration = moment(stopValue).format('HH:mm').valueOf() - moment(startValue).format('HH:mm').valueOf();

I assume the issue here is that my startValue and stopValue need to be converted to a different format first, since they are currently string values? So, how can I convert a string value of "1:12" to be something moment can use?

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

0

There are two problems with your code:

  1. Invalid parsing

    Your time inputs are not in a standard format that Moment recognizes, so you'll have to use a formatted parse to explain your times to it.

  2. formatting as string before of calling valueOf.

    .format() converts your Moment object to a string, and strings can't be subtracted. To solve this, you can just drop the .format() call. Instead, you can also use .diff(), that will compute the difference for you.

So, you can use either of these:

const msDuration = moment(stopValue, "H:mm").valueOf() - moment(startValue, "H:mm").valueOf()
const msDuration = moment(stopValue, "H:mm") - moment(startValue, "H:mm") // Subtracting will implicitly call .valueOf()
const msDuration = moment(stopValue, "H:mm").diff(moment(startValue, "H:mm"))
about 4 years ago · Juan Pablo Isaza Relatório

0

Based on your comments above, I recognize that you are receiving the times as a response in the following format: "HH:mm".

If the actual Date doesn't really matter, then you can convert it like this (JsFiddle):

const startValue = "1:12";
const stopValue = "2:10"; // for a duration of 58 minutes
const start = { hour: startValue.split(":")[0], minute: startValue.split(":")[0] }
const stop = { hour: stopValue .split(":")[0], minute: stopValue .split(":")[0] }

const msDuration = moment().hours(stop.hour).minutes(stop.minute).valueOf() - moment().hours(start.hour).minutes(start.minute).valueOf(); //you might get 1 ms less. so jest set also ms to 0
const msDurationA = moment().hours(stop.hour).minutes(stop.minute).milliseconds(0).valueOf() - moment().hours(start.hour).minutes(start.minute).milliseconds(0).valueOf();

So basically you are taking the current date and mutate the hours and minutes, so you can work with moment.Js.

Although my question is, why do you necessary need moment? you can also do it in native JS:

const startValue = "1:12";
const stopValue = "2:10"; // for a duration of 58 minutes

const start = { hour: +startValue.split(":")[0], minute: +startValue.split(":")[1] };
const stop = { hour: +stopValue.split(":")[0], minute: +stopValue.split(":")[1] };

const msDuration = (stop.hour * 3600000 + stop.minute * 60000) - (start.hour * 3600000 + start.minute * 60000);

console.log("msDuartion: ", msDuration);

about 4 years ago · Juan Pablo Isaza Relatório

0

Using vanilla JS:

function getMilliSecs(text) {
  const spl = text.split(":");
  return parseInt(spl[0])*60*60*1000 + parseInt(spl[1])*60*1000; 
}

function getMilliSecsDuration(start, stop) {
  return getMilliSecs(stop) - getMilliSecs(start);
}
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