Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for time left in the day?

I understand how to work countdown timers and date timers to an extent (to a specified date i.e YYYY-MM-DD) but I'm working on a web development college project where I wish for one of my web pages (JSP file) to have a countdown timer with the number of seconds left in the day from when the web application launches.

The web page will also include an Ajax function where the user can click a button and a random motivational message will appear (this particular piece of code I know, but it's just to give you an idea of why I want this countdown timer).

like image 772
John Deegan Avatar asked Jun 14 '26 11:06

John Deegan


2 Answers

Moment.js is a great library for date math. http://momentjs.com/

Using Moment, you could do a one liner like this.

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script>
  document.write(moment.duration(moment().add(1, 'day').startOf('day').diff(moment())).asSeconds())
</script>

or an easier to understand version:

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script>
  var now = moment(),
    tomorrow = moment().add(1, 'day').startOf('day'),
    difference = moment.duration(tomorrow.diff(now))

  document.write(difference.asSeconds())
</script>
like image 85
Matt Roman Avatar answered Jun 16 '26 23:06

Matt Roman


UPDATED

Simply compare the Date object you get from Date.now() with the date of tomorrow (which you create from the first date object, adding one day);

var actualTime = new Date(Date.now());

var endOfDay = new Date(actualTime.getFullYear(), actualTime.getMonth(), actualTime.getDate() + 1, 0, 0, 0);


var timeRemaining = endOfDay.getTime() - actualTime.getTime();

document.getElementById('timeRemaining').appendChild(document.createTextNode(timeRemaining / 1000 + " seconds or " + timeRemaining / 1000 / 60 / 60 + " hours"));

document.getElementById('dayProgression').value = 1 - (timeRemaining / 1000 / 60 / 60 / 24);
<span id="timeRemaining"></span>

<div>
  <span>How much of the day has passed:</span>
  <progress id="dayProgression" value="0"></progress>
</div>

Example JSFiddle

like image 34
Jeff Noel Avatar answered Jun 16 '26 22:06

Jeff Noel