检查时间是否在javascript中的小时和分钟的两个值之间 [英] Check if time is between two values with hours and minutes in javascript

查看:25
本文介绍了检查时间是否在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; } 

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

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

推荐答案

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

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

这篇关于检查时间是否在javascript中的小时和分钟的两个值之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆