2012-01-31 99 views
2

当用户访问一个页面时,我需要检查当前时间是在一个工作日上午9点到下午5点之间,并显示使用jquery/javascript.But的东西,但我不知道如何检查。如何使用jQuery/javascript检查当前时间是否在特定范围内?

有人可以帮忙吗?

感谢

+2

你有没有看着[为JavaScript文件Date对象?](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) – Pointy 2012-01-31 14:33:14

回答

11

这样应该可以帮助:

function checkTime() { 
    var d = new Date(); // current time 
    var hours = d.getHours(); 
    var mins = d.getMinutes(); 
    var day = d.getDay(); 

    return day >= 1 
     && day <= 5 
     && hours >= 9 
     && (hours < 17 || hours === 17 && mins <= 30); 
} 
+1

express $ .inArray(d.getDate()),[1 ..])总是计算为true,因为它会在Sat-Sun返回-1。因此它不会过滤周数。编辑修补程序将明确地仅通过getDay约定选择1-5或周一至周五的日期。 – stanzheng 2015-02-26 22:01:10

+1

谢谢@stanzheng :-)更新 – jabclab 2015-02-27 16:10:52

1

利用当前的时间,你可以做这样的事情:

var now = new Date(), 
    day = now.getDay(), 
    hours = now.getHours(); 

//Check if day is Mon-Fri 
if(0 < day < 6) { 
    //check between 9am and 5pm 
    if(9 <= hours <= 17) { 
    if(hours !== 17 || now.getMinutes() <= 30) { 
      //your jQuery code here 
    } 
    } 
} 
0
var now = new Date(); 
var dayOfWeek = now.getDay(); 
if(dayOfWeek > 0 && dayOfWeek < 6){ 
    //falls on a weekday 
    if (now.getHours() > 9 && (now.getHours() < 17 && now.getMinutes() < 30)) { 
     //it's in schedule 
    } 
} 
1

只是增加了两个美分,至一小时检查...

我个人认为,更好的办法是检查是否是在范围:乙 - C:d ...

// check if h:m is in the range of a:b-c:d 
 
// does not support over-night checking like 23:00-1:00am 
 
function checkTime (h,m,a,b,c,d){ 
 
     if (a > c || ((a == c) && (b > d))) { 
 
      // not a valid input 
 
     } else { 
 
      if (h > a && h < c) { 
 
       return true; 
 
      } else if (h == a && m >= b) { 
 
       return true; 
 
      } else if (h == c && m <= d) { 
 
       return true; 
 
      } else { 
 
       return false; 
 
      } 
 
     } 
 
}