How to check if current time falls within a specific range on a week day using jquery/javascript?
18,210
Solution 1
This should hopefully help:
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);
}
Solution 2
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
}
}
Solution 3
Using the current time you could do something like this:
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
}
}
}
Solution 4
Just added two cents to the hour checking...
I personally think that a better way would be to check if is in the range of a:b--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;
}
}
}
Author by
kranthi
Updated on June 19, 2022Comments
-
kranthi almost 2 years
When a user visits a page I need to check if the current time falls between 9:00 am and 5:30pm on a weekday and display something using jquery/javascript.But I am not sure how can check that.
Could someone please help?
Thanks
-
StanleyZheng about 9 yearsthe express $.inArray(d.getDate()),[1..]) always evaluates to true because it returns -1 for Sat-Sun. Therefore it will not filter by week days. The edit fix will explicitly only pick days between 1-5 or Mon-Friday by getDay convention.