Alligator
Alligator

Reputation: 730

Check if time is between two values with hours and minutes in javascript

I need to check if a time is between a start and end time. All times are on the same day, so date is not important. I'm able to compare hours, but I'm unsure how to add in minutes to the start and end times.

var thedate = new Date(); 
var dayofweek = thedate.getUTCDay(); 
var hourofday = thedate.getUTCHours(); 
var minutesofday = date.getMinutes();
function inTime() { if (dayofweek != 0 && dayofweek != 7 && (hourofday > 13 && hourofday < 20)) { return true; } return false; } 

If I want to check whether the time is between 13:05 and 19:57, how would I add the minutes to my inTime function? If I add them to the if statement, it fails to work:

 function inTime() { if (dayofweek != 0 && dayofweek != 7 && ((hourofday > 13 && minutesofday > 5) && (hourofday < 20 && minutesofday < 57))) { return true; } return false; } 

Upvotes: 10

Views: 24606

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

If you're saying you want to check if the time "now" is between two times, you can express those times as minutes-since-midnight (hours * 60 + minutes), and the check is quite straightforward.

For instance, is it between 8:30 a.m. (inclusive) and 5:00 p.m. (exclusive):

var start =  8 * 60 + 30;
var end   = 17 * 60 + 0;

function inTime() {
  var now = new Date();
  var time = now.getHours() * 60 + now.getMinutes();
  return time >= start && time < end;
}

console.log(inTime());

The above uses local time; if you want to check UTC instead, just use the equivalent UTC methods.

Upvotes: 5

Tuhin Paul
Tuhin Paul

Reputation: 558

Convert times to milliseconds and then you can compare easily.

short version:

if(timeToCheck.getTime() >= startTime.getTime() &&
        timeToCheck.getTime() <= endTime.getTime()) {
    // ...
}

OR:

let startTimeMilli = startTime.getTime();
let endTimeMilli = endTime.getTime();
let timeToCheckMilli = timeToCheck.getTime();

// change >= to > or <= to < as you need
if (timeToCheckMilli >= startTimeMilli && timeToCheckMilli <= endTimeMilli) {
    // do your things
}

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138267

If its 14:04 your condition will fail as 4 is smaller 5. The simplest would probably be to just take the full minutes of the day:

 const start = 13 * 60 + 5;
 const end =  19 * 60 + 57;
 const date = new Date(); 
 const now = date.getHours() * 60 + date.getMinutes();

 if(start <= now && now <= end)
   alert("in time");

Upvotes: 22

Related Questions