Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 309
Alligator Avatar asked Apr 04 '18 15:04

Alligator


2 Answers

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");
like image 160
Jonas Wilms Avatar answered Sep 22 '22 00:09

Jonas Wilms


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.

like image 27
T.J. Crowder Avatar answered Sep 20 '22 00:09

T.J. Crowder