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

717
Visualizações
calculating hours between two dates and time in javascript

I am trying to calculate total hours and minute different two different date and time:

below is my code:

let startShiftTime = moment(StartTime, ['DD-MM-YYYY h:mm:ss A'])
    .utcOffset(0, false)
    .format('DD-MM-YYYY hh:mm:ss A');

let endShiftTime = moment(EndTime, ['DD-MM-YYYY h:mm:ss A'])
    .utcOffset(0, false)
    .format('DD-MM-YYYY hh:mm:ss A');

var TotalSeconds = moment(startShiftTime, 'DD-MM-YYYY hh:mm:ss A')
    .utcOffset(0, false)
    .diff(
        moment(endShiftTime, 'DD-MM-YYYY hh:mm:ss A').utcOffset(0, false),
        'seconds',
    );

var hours = Math.floor(TotalSeconds / 3600);
var minutes = Math.floor((TotalSeconds / 60) % 60);
console.log(
    'startShiftTime: ',
    startShiftTime,
    ' endShiftTime: ',
    endShiftTime,
    ' hours: ',
    hours,
    ' minutes: ',
    minutes,
);

I am getting hours and minutes in all cases apart from case time difference is 1 hours or else

console output:

startShiftTime:  02-12-2021 09:00:00 AM  endShiftTime:  01-12-2021 09:30:00 PM  hours:  11  minutes:  30
startShiftTime:  02-12-2021 04:30:00 PM  endShiftTime:  02-12-2021 05:00:00 PM  hours:  -1  minutes:  -30

see in the second output... time difference is only 30 mins.. but in hours I am getting as 1

I am not able to understand where I am making mistake

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

0

You don't need to do those calculations by yourself, but you can use the moment.duration API:

const startShiftTime = moment('01-12-2021 09:00:00 AM', 'DD-MM-YYYY hh:mm:ss A');
const endShiftTime = moment('01-12-2021 09:30:00 AM', 'DD-MM-YYYY hh:mm:ss A');

const duration = moment.duration(startShiftTime.diff(endShiftTime));

console.log('as hours: ' + duration.asHours(), 'as minutes: ' + duration.asMinutes());
console.log('hours: ' + duration.hours(), 'minutes: ' + duration.minutes());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

PS: You get negative values because the difference is done on the start time, which is smaller than the end time. If you want positive values then you just inverse the diff: endShiftTime.diff(startShiftTime)

about 4 years ago · Juan Pablo Isaza Relatório

0

Why are startShiftTime and endShiftTime formatted strings instead of instances of moment. You end up parsing them again later.

You are calculating the difference between times the wrong way round by it should be.

endShiftTime
    .diff(startShiftTime,'seconds')

This then leads to the obvious question, why is the first example calculating correctly... It because the end shift time is before the start time, this doesn't make any sense.

Swapping the start and end times in your first example then result in the correct answer in both instances.

function calculate(StartTime, EndTime) {

  let startShiftTime = moment(StartTime, ['DD-MM-YYYY h:mm:ss A'])
    .utcOffset(0, false);

  let endShiftTime = moment(EndTime, ['DD-MM-YYYY h:mm:ss A'])
    .utcOffset(0, false);

  var TotalSeconds = endShiftTime
    .diff(startShiftTime,'seconds');
    
  var hours = Math.floor(TotalSeconds / 3600);
  var minutes = Math.floor((TotalSeconds / 60) % 60);
  console.log(`startShiftTime: ${startShiftTime.format('DD-MM-YYYY h:mm:ss A')} endShiftTime: ${endShiftTime.format('DD-MM-YYYY h:mm:ss A')} hours: ${hours} minutes: ${minutes}`);
}

calculate('01-12-2021 09:30:00 PM', '02-12-2021 09:00:00 AM');
calculate('02-12-2021 04:30:00 PM', '02-12-2021 05:00:00 PM');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

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