0

http://jsbin.com/ocuceb/6/edit

上面的链接是完整代码所在的位置,我正在尝试获取一个倒计时计时器,以了解在营业结束前还剩多少小时和分钟。

function countDown() {
  var d = new Date();
  var hour = d.getHours();
    if(hour<10){hour="0"+hour;}
      else if(hour>12){hour=hour - 12;}
      var minutes = d.getMinutes();
    if(minutes<10){minutes="0"+minutes;}
      var seconds = d.getSeconds();
    if(seconds<10){seconds="0"+seconds;}
  var open = weekday[day.getDay()].open.replace(/am/g,'');
  var close = weekday[day.getDay()].close.replace(/pm/g,'');
  open = parseInt(open,10);
  close = parseInt(close,10); 
 //confused here!  
   var timeClose = close;
   var timeRemaining = Math.floor(d.getHours() - timeClose);
   document.write('<br><br>Close At: '+timeClose+"pm<br>Time Remaining:"+timeRemaining);
  }

这就是我遇到麻烦的地方,我可以得到打开的时间和关闭的时间。最初我试过这个

 var timeClose = parseInt(close+':00:00',10);
 var difference = Math.floor(d.getDay() - timeClose);

当然这没有用,它要么是 Undefined 要么是 NaN 我不知道该怎么做,时间对我来说是全新的,尽管客户要求这样做,但我从来不需要这个。它说明实际时间,关闭时间,并显示图像,如果时间在开放到关闭时间(基本上是开放式霓虹灯)和过去关闭时(关闭的霓虹灯)......我想它会非常简单,虽然我有这么棘手的角落要通过。

4

2 回答 2

1

JavaScript 时间不考虑 12 小时格式。它以 24 小时格式思考。更改您的对象数组以反映(22 是晚上 10 点):

hours[0]= {open:"8:00:00",close:"22:00:00"};
hours[1]={open:"8:00:00",close:"22:00:00"};
hours[2]={open:"8:00:00",close:"22:00:00"};
hours[3]={open:"8:00:00",close:"22:00:00"};
hours[4]={open:"8:00:00",close:"22:00:00"};
hours[5]={open:"8:00:00",close:"22:00:00"};
hours[6]={open:"8:00:00",close:"22:00:00"};

此外,解析这样的 int 可能会导致问题:

var timeClose = parseInt(close+':00:00',10);

您应该substring使用冒号之间的所有内容来获得所需的小时数或分钟数。

var timeClose = parseInt(open.substring(0,open.indexOf(":")),10);

此外,按照您的设置方式,在营业时间(或晚上 10 点之前),您将始终得到一个负数,因为您从关闭时间中减去当前时间。如果是晚上 8 点,关门时间是晚上 10 点,我们还剩 -2 小时?将操作数切换为getHours减去time

var timeRemaining = Math.floor(timeClose - d.getHours());

之后,您可能可以检查timeRemaining负值。如果为负数,则表示业务已关闭,您可以修改输出消息以反映这种情况,即

var timeRemaining = Math.floor(timeClose - d.getHours());
if (timeRemaining < 0) {
    output = "Sorry we are closed already";
} else {
    output = "You have " + timeRemaining + " to come in and shop till you drop";
}
于 2013-06-25T01:14:13.060 回答
1

我认为更简单的方法是这样的

var now=new Date();
var closing=new Date(now.getFullYear(),now.getMonth(),now.getDate(),21);//Set this to 10:00pm on the present day
var diff=closing-now;//Time difference in milliseconds
if(now.getHours<7){
  //It's before opening time
}
else if(diff<0){
  //It's after closing time
}
else{
  var hours=Math.floor(diff/(1000*60*60));
  diff=diff%(1000*60*60);
  var mins=Math.floor(diff/(1000*60));
  diff=diff%(1000*60);
  var secs=Math.floor(diff/(1000));
}

这是时间对象的参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

于 2013-06-25T01:20:08.360 回答