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

190
Visualizações
Time returns always 0 when using a custom date

I need to start a time from a start date for n number of days. When I use date (now) inside set interval function it works but if I use the date from parameter then the time is always 0.

let startDate = new Date().getTime();

startTimer(days,startDate) {

  let today = new Date().getTime();
  let countDown = this.addDays(today,days);
  let countDown2 = new Date(countDown).getTime();

  let x = setInterval(() => {

  let now = new Date().getTime();
  //let distance = countDown2 - startDate; //not working when i use startDate here
  let distance = countDown2 - now; //working when i use 'now'
  let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  this.displayDate = hours + "h";

  if(distance < 0) {
    clearInterval(x);
    this.displayDate = "Expired";
     }
   })    
}

  addDays(date, days) {
   var result = new Date(date);
   result.setDate(result.getDate() + days);
  return result;
 }

when i use startDate as 10 from parameter, the o/p is 10d: 0h: 0m: 0s (time always 0)

when i use any date other than now inside setinterval time in o/p will be 0 say 10d: 0h: 0m: 0s

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

0

remove the init of x on the interval, and make sure you add a time that the interval is base off at the end of it...

setInterval(() =>

// end of interval
}, 1000) // 1000ms = 1 second

and the function needs to return something... in this example i included the returns in a console.log() just to visualize it but removing that is easy.

if(distance < 0) {
  clearInterval(x);
  return console.log("Expired")   
} else {
  return console.log(count_days + "d: " + hours + "h: " + minutes + "m: " + seconds + "s")
}  

after those changes you should be able to call the startTimer() function and it should work just fine...

startTimer(10, startDate)

/* OUTPUT
9d: 23h: 59m: 58s
9d: 23h: 59m: 57s
9d: 23h: 59m: 56s
9d: 23h: 59m: 55s
9d: 23h: 59m: 54s
*/
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