如何从下午2点到下午2点开始我的JS倒计时?

时间:2018-01-17 03:15:15

标签: javascript

目前,它的工作时间是上午12点到12点,但我希望它在下午2点到下午2点之间运行。有可能吗?

setInterval(
  function() {
    var d = new Date();
    var hours = 23 - d.getHours();
    var min = 59 - d.getMinutes();
    if ((min + '').length == 1) {
      min = '0' + min;
    }
    var sec = 59 - d.getSeconds();
    if ((sec + '').length == 1) {
      sec = '0' + sec;
    }
    $('#the-final-countdown').html(hours + ':' + min + ':' + sec);
  },
  1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="the-final-countdown"></div>

2 个答案:

答案 0 :(得分:0)

setInterval(function time(){
      var d = new Date();
      if(d.getHours()<=13){
        var hours = (13 - d.getHours());
       }else{
         var hours = (23+14 - d.getHours())
       }
      var min = 59 - d.getMinutes();
      if((min + '').length == 1){
        min = '0' + min;
      }
      var sec = 59 - d.getSeconds();
      if((sec + '').length == 1){
            sec = '0' + sec;
      }
      jQuery('#the-final-countdown p').html(hours+':'+min+':'+sec)
    }, 1000);

答案 1 :(得分:0)

创建一个倒计时到14:00的计数的一种简单方法是获得现在和下一次14:00之间的差异,然后转换为h:mm:ss,例如

// Returns milliseconds from date until next 1400
// Default for date is current time
function next1400(date) {
  var now = date || new Date();
  var end = new Date(now);
  end.setHours(end.getHours() < 14? 14 : 38, 0, 0, 0);
  return formatTime(end - now);
}

// Format milliseconds as H:mm:ss
function formatTime(ms) {
  var s = Math.ceil(ms/1e3);
  function z(n){return (n<10?'0':'')+n}
  return (s/3.6e3 | 0) + ':' +
         z((s%3.6e3)/60 | 0) + ':' +
         z(s%60) ;       
}

// QnD way to call each second. This will skip occasionally, 
// there are better ways.
setInterval(function(){
  console.log(next1400());
}, 1000);