Reputation: 39
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).
Upvotes: 2
Views: 7960
Reputation: 1981
Try to use this Javascript code:
var year = 2015 , month = 5 , day = 15;
var date = new Date();
var enddate = new Date(year , month , day);
document.write( date - enddate );
You can edit this code for your site.
Upvotes: 1
Reputation: 7618
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>
Upvotes: 2
Reputation: 436
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>
Upvotes: 6