检查时间是否在javascript中的小时和分钟的两个值之间

All*_*tor 5 javascript time

我需要检查时间是否在开始时间和结束时间之间。所有时间都在同一天,所以日期并不重要。我可以比较小时数,但我不确定如何在开始和结束时间中添加分钟数。

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; } 
Run Code Online (Sandbox Code Playgroud)

如果我想检查时间是否在 13:05 和 19:57 之间,我如何将分钟添加到我的 inTime 函数中?如果我将它们添加到 if 语句中,它将无法工作:

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

Jon*_*lms 12

如果它14:04你的条件会失败,因为4它更小5。最简单的方法可能是花一天中的全部时间:

 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");
Run Code Online (Sandbox Code Playgroud)

  • 显然,有两个人决定对*每个*的答案投反对票(第三个人对其中一个投反对票)。**叹** (3认同)

T.J*_*der 5

如果您想检查“现在”时间是否在两个时间之间,则可以将这些时间表示为自午夜以来的分钟数 ( hours * 60 + minutes),并且检查非常简单。

例如,是否在上午 8:30(含)和下午 5:00(不含)之间:

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());
Run Code Online (Sandbox Code Playgroud)

以上使用当地时间;如果您想检查 UTC,只需使用等效的 UTC 方法即可。