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

302
Visualizações
How to get the time difference in hours between two Date.now()?

I have an object which updates often with time series stamps like:

obj = [{
  "value": 48.52062,
  "timestamp": 1652848223325
},
{
  "value": 43.33057,
  "timestamp": 1652838323281
},
{
  "value": 55.95403,
  "timestamp": 1652833823275
},
{
  "value": 51.71021,
  "timestamp": 1652830223280
},
{
  "value": 58.44382,
  "timestamp": 1652829323276
}]

How can I get the number of hours between these timestamps? I am trying something like this:

 var timeStart = new Date(1652848686623).getHours();
 var timeEnd = new Date(1652836523287).getHours(); 
 var hourDiff = timeEnd - timeStart;
 console.log(hourDiff)
But I am getting 21 as output which is wrong, it is just 3.

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

0

This is because the .getHours() method of a Date object simply returns the hour of the day that the object represents. It does not return the total number of hours since the epoch, and therefore you cannot simply subtract the two values to obtain a meaningful result.

You can achieve what you want with a simple subtraction and division:

const timeStart = new Date(1652836523287)
const timeEnd   = new Date(1652848686623)
const hourDiff  = (timeEnd - timeStart) / 1000 / 60 / 60

NOTE that I swapped the two timestamps since clearly 165284... is after 165283....

about 4 years ago · Juan Pablo Isaza Relatório

0

You can not just use getHours() on Date, and substract with them, because the "hours" is time of day, not the "absolute" time.

Instead, You can just substract the end timestamp with start timestamp in your case, then just divide it by 3600000 (or 1000 * 60 * 60) to convert it to hour.

function getHourDiff(start, end) {
   return Math.floor((end - start) / 3600000)
}

const timeStart = 1652836523287;
const timeEnd = 1652848686623

console.log(getHourDiff(timeStart, timeEnd));

about 4 years ago · Juan Pablo Isaza Relatório

0

const timeStart = new Date(1652836523287)
const timeEnd   = new Date(1652848686623)
const hourDiff  = Math.abs(timeEnd - timeStart) / 36e5
console.log(hourDiff)

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