问题描述
所以有很多关于如何计算两个日期之间的时间的例子。
So there's plenty of examples on how to calculate the time between two dates.
但在我的例子中,我有一个日期X.假设今天是。
X有时间关联它,例如08:00(或者我从 .getHours()
)中获得回复
But in my case, I have a date X. Let's say it's today.X has a time associate to it, e.g. 08:00 (Or what I get back from .getHours()
)
我需要知道,如果 X 的小时在开始时间(例如07:00)和结束时间之间(说12:00)
I need to know if the hours of X are between a start hour (say "07:00") and an end hour (say "12:00")
X将始终通过 getHours()
检索范围的开始和结束时间具有固定格式(例如07:00和12:00 )
X will be always retrieved via getHours()
The start and end hour of the range have a fixed format (e.g. "07:00" and "12:00")
性能是一个问题,所以任何性能更好是首选(例如,如果它暗示使用时刻
,没关系,但是如果一个自定义函数的表现会更好,那么我们就想要这样做)
Performance is an issue, so whatever performs better is preferred (e.g. if it implies using moment
, that's fine, but if a custom function would perform better, we want that)
我的第一个方法是将格式修改为 .getHours()
到一个数字,同样的范围小时,然后计算...我觉得这种方法我有麻烦的一些特殊情况我可能不知道?
My first approach would be, as the formats are fixed, to transform the .getHours()
to a number, likewise for the range hours, and then calculate...I feel this approach my have trouble with some special cases I may not be aware of?
推荐答案
如果您想要查看部分时间,请考虑将小时转换为分钟,如下所示。你将如何处理午夜过后的范围?例如23:30至01:30。
If you want to check part hours, consider converting the hours to minutes, something like the following. How will you deal with ranges that go over midnight? e.g. 23:30 to 01:30.
/* Determine if the current time is between two provided hours
** @param {string} h0 - time in format h:mm
** @param {string} h1 - time in format h:mm
** @returns {boolean} true if the current time is between or equal to h0 and h1
*/
function betweenHours(h0, h1) {
var now = new Date();
var mins = now.getHours()*60 + now.getMinutes();
return toMins(h0) <= mins && mins <= toMins(h1);
}
/* Convert hours to minutes
** @param {string} h - time in format h:mm
** @returns {number} time converted to minutes
*/
function toMins(h) {
var b = h.split(':')
return b[0]*60 + +b[1];
}
<form>
Start time (h:mm)<input name="startHours">
<br>
End time (h:mm)<input name="endHours">
<br>
<button type="button" onclick="
this.form.inRange.value = betweenHours(this.form.startHours.value, this.form.endHours.value);
">Check range</button>
<br>
Currently in range? <input name="inRange" readonly>
</form>
这篇关于javascript:评估如果给定的小时是在两个小时之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!