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

北战南征 提交于 2021-01-03 06:35:11

问题


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; } 

回答1:


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");



回答2:


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.




回答3:


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
}


来源:https://stackoverflow.com/questions/49655310/check-if-time-is-between-two-values-with-hours-and-minutes-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!