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我不知道如何解决这个问题,时间对我来说都是新的,虽然客户要求这个,但我从未需要这个。它指出实际时间,它们关闭的时间,并显示图像,如果时间是在开放到关闭时间(基本上是开放的霓虹灯)和过去关闭(一个封闭的霓虹灯)...我认为它会很简单,虽然我有这么棘手的角落要通过。
答案 0 :(得分: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";
}
答案 1 :(得分: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
的参考