我有例如2次:10:00和1:00现在我要检查,如果当前时间... ...是这两个时间之间的JavaScript
。的问题是,在这种情况下,关闭时间是一个第二天所以其openingstime之前。我怎么能这样做出于某种原因,我不能解决这个得到正确的道路。
我甲肝efound,这可以解决这个问题:
VAR开始=新的日期(2012,6,20,13).getTime();。现在VAR =新的日期()的getTime();VAR结束=新的日期(2012,6,21,2).getTime();如果((&开始LT;现在)及及(今<结束)){ 的console.log(开);}其他{ 的console.log(封闭);}
但我怎么能有2个字符串格式,如10:00和2:00做,因为我没有看到一个选项,独自把时间
变种D =新的日期();变种D =新的日期(毫秒);变种D =新的日期(dateString);变种D =新的日期(年,月,日,时,分,秒,毫秒);
解决方案
您可以使用一个简单的函数类似这样的,因为你的0:00时转换为数字分钟:
函数getMinutes(STR){ VAR时间= str.split(':'); 返回时间[0] * 60 +时间[1] * 1;}
和类似的功能来获得当前的时间到相同的形式,以进行比较:
函数getMinutesNow(){ VAR timeNow =新的日期(); 返回timeNow.getHours()* 60 + timeNow.getMinutes();}
然后都转换开启和关闭时间,如果它发生闭时间开标时间前24小时添加到它。
VAR现在= getMinutesNow();VAR开始= getMinutes('10:00');VAR结束= getMinutes('2:00');如果(开始>结束)结束+ = getMinutes('24:00');如果((现>启动)及及(今<结束)){//你的code在这里
I have 2 times for example: 10:00 and 1:00 now i want to check if current time... is between these 2 times in javascript.
The problem is that the closing time in this case is a next day so its before the openingstime. How can i do this the proper way for some reason i can not get around this.
i hav efound that this could solve it:
var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();
if( (start < now ) && (now < end )) {
console.log("opened");
}
else {
console.log("closed");
}
but how can i do it with 2 string formats like 10:00 and 2:00 because i do not see a option to put a time alone
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
解决方案
You could use a simple function like this to convert your time to a number of minutes since 0:00:
function getMinutes(str) {
var time = str.split(':');
return time[0]*60+time[1]*1;
}
And a similar function to get the current time into the same form in order to compare:
function getMinutesNow() {
var timeNow = new Date();
return timeNow.getHours()*60+timeNow.getMinutes();
}
Then convert both opening and closing time and, if it happens that closing time is before opening time, add 24 hours to it.
var now = getMinutesNow();
var start = getMinutes('10:00');
var end = getMinutes('2:00');
if (start > end) end += getMinutes('24:00');
if ((now > start) && (now < end)) { // your code here
相关推荐
最新文章