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; }
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With