Javascript for time left in the day?

陌路散爱 提交于 2019-12-02 09:56:14

问题


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).


回答1:


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>



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/27380687/javascript-for-time-left-in-the-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!