How to check if current time falls within a specific range on a week day using jquery/javascript?
Asked Answered
B

7

12

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

Babbittry answered 31/1, 2012 at 14:30 Comment(1)
Have you looked at the documentation for JavaScript Date objects?Feudality
D
23

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);
}
Dasteel answered 31/1, 2012 at 14:37 Comment(1)
the 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.Bills
R
4

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
     }
  }
}
Roadrunner answered 31/1, 2012 at 14:37 Comment(0)
M
3
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
   }
}
Manta answered 31/1, 2012 at 14:37 Comment(0)
L
2

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;
           }
      }
}
Lavin answered 1/10, 2015 at 20:46 Comment(0)
C
0

I had a requirement where I needed to find if time in one date object lies within other two. (Date didn't matter, instead only time).

I did it this way, I thought it might help someone.

/*
* d, start and end all are Date objects.
*/
const checkIfTimeIsInRange = (d, start, end) => {
    if (start.getHours() < d.getHours() && d.getHours() < end.getHours()) {
        return true;
    } else if (start.getHours() == d.getHours()) {
        if (d.getHours() == end.getHours()) {
            if(start.getMinutes() <= d.getMinutes() && d.getMinutes() <= end.getMinutes()) {    
                return true
            } else {
                return false
            }
        } else if(start.getMinutes() <= d.getMinutes()) {
            return true
        } else {
            return false
        }
    } else if (d.getHours() == end.getHours()) {
        if(d.getMinutes() <= end.getMinutes()) {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

P.S. Any improvements, suggestions are welcome.

Customable answered 19/2, 2020 at 13:10 Comment(0)
D
0

document.getElementById('tmp_button-48523').addEventListener('click', function() {
let d = new Date();
let localTime = d.getTime();
let localOffset = d.getTimezoneOffset() * 60000;
let utc = localTime + localOffset;
let target_offset = -7;//PST from UTC 7 hours behind right now, will need to fix for daylight
let los_angles = utc+(3600000*target_offset);
nd = new Date(los_angles);
let current_day = nd.getDay();
let hours = nd.getHours();
let mins = nd.getMinutes();

alert("los_angles time is " + nd.toLocaleString());
alert("Day is "+current_day);

if(current_day==2 && hours >= 14 && hours <=15  )
if(hours!=15 && mins >= 32)
fbq('track', 'LT-Login');

}, false);

function fbq(p1,p2){
alert(p1);
}
<button id="tmp_button-48523">
Click me!
</button>
Diplomatic answered 24/3, 2020 at 22:0 Comment(0)
D
0

Here is another approach in case the range goes past midnight (e.g. 22:00 - 02:00).

The times are converted to numbers and filled into an array.

If the range is: '10:00 - 12:00' -> the array is [1000, 1200].

If the range is: '22:00 - 02:00' -> the array is [2200, 2400, 0, 200].

Here is the code:

let startTime = '14:10';
let endTime = '03:30';

let inRange = false;

let now = new Date();
let currentTime = Number(now.getHours() + '' + ('0' + now.getMinutes()).slice(-2));

// play with currentTime
// currentTime = Number('02:00'.split(':').join(''));

let startRangeTime = Number(startTime.split(':').join(''));
let endRangeTime = Number(endTime.split(':').join(''));

let timestamps = [];
timestamps[0] = startRangeTime;
timestamps[1] = endRangeTime;
// build four item array if endDate is in next day 
if (startRangeTime > endRangeTime) {
  timestamps[1] = 2400;
  timestamps[2] = 0;
  timestamps[3] = endRangeTime;
}

if (timestamps[0] <= currentTime && timestamps[1] >= currentTime || (timestamps.length > 2 && timestamps[2] <= currentTime && timestamps[3] >= currentTime))
  inRange = true;

console.log('inRange:', inRange)
Delacourt answered 5/5, 2023 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.