How do I make a countdown chronometer to a date?

Asked

Viewed 925 times

4

Good is the following I have a following date with an hour, and I would like to know how I could make a countdown chronometer, with days hours and minutes and seconds until I reach that date and that time.

Example: The date set in javascript is 18/08/2016 at 20:02 and 16 seconds, that is, the chronometer will have to show how many days, minutes and seconds to reach this date with countdown in real time.

How can I do this with javascript?

Thank you.

2 answers

1

That’s the least to start with, but I think it already helps.

//aqui vai sempre ser a hora atual
var startDate = new Date();
//como exemplo vou definir a data de fim com base na data atual
var endDate = new Date();
endDate.setDate(endDate.getDate()+5);

//aqui é a diferenca entre as datas, basicamente é com isso que voce calcula o tempo restante
var dateDiff;
var days, hours, minutes, seconds;
var $day = $('#dias');
var $hour = $('#horas');
var $minute = $('#minutos');
var $second = $('#segundos');
var $debug = $('#debug');
var timer;

function update(){
	dateDiff = endDate - startDate;
  dateDiff = dateDiff / 1000;
  
	seconds = Math.floor((dateDiff % 60));
  
  dateDiff = dateDiff / 60;
  minutes = Math.floor((dateDiff % 60));
	
  dateDiff = dateDiff / 60;
  hours = Math.floor((dateDiff%24));
  
	days = Math.floor(dateDiff/24);
  
  $day.text(days);
  $hour.text(hours);
  $minute.text(minutes);
  $second.text(seconds);
  
  startDate.setSeconds(startDate.getSeconds()+1);
}
update();
timer = setInterval(update, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="dias"></div>
<div id="horas"></div>
<div id="minutos"></div>
<div id="segundos"></div>
<div id="debug"></div>

1

You can use some blibioteca of Countdown, below follows an implementation used the blibioteca developed by Hugo Giraudel

Countdown.js

new Countdown({
  selector: '#countdown',
  msgAfter: "O Evento Iniciou!",
  msgPattern: "{days} dias, {hours} horas, {minutes} minutos e {seconds} segundos até a data do evento!",
  dateEnd: new Date("2016-08-18T20:02:16"),
  onEnd: function() {
    alert('O Evento Iniciou!');
  }
});
<script src="https://rawgit.com/HugoGiraudel/Countdown.js/master/countdown.js"></script>
<div id="countdown"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.