时间在间隔内吗?

时间:2018-10-06 14:51:31

标签: javascript time

我正在尝试检查时间是否在时间间隔内。

我有一个 currentTime -变量(作为字符串),其格式完全如下:

let currentTime = "08:45"

我还有一个 timeInterval -变量(作为字符串),其格式如下:

let timeInterval = "08:40 - 09:20"

我要检测的是指定变量“ currentTime”中的时间适合给定“ time interval”中的时间?


到目前为止,我尝试过的事情是这样的:

let isInsideInterval = function(currentTime, timeInterval) {
  let currentHour = parseInt(currentTime.split(":")[0]),
      currentMinute = parseInt(currentTime.split(":")[1]),
      interval = {
        startHour: parseInt(timeInterval.split(" - ")[0].split(":")[0]),
        startMinute: parseInt(timeInterval.split(" - ")[0].split(":")[1]),
        endHour: parseInt(timeInterval.split(" - ")[1].split(":")[0]),
        endMinute: parseInt(timeInterval.split(" - ")[1].split(":")[1])
    }
  
  let isAfterStart = (currentHour*60+currentMinute) - (interval.startHour*60+interval.startMinute) > 0 ? 1 : 0;
  let isAfterEnd = (currentHour*60+currentMinute) - (interval.endHour*60+interval.endMinute) < 0 ? 1 : 0;
  return isAfterStart && !isAfterEnd;
}

let currentTime_1 = "08:45"
let timeInterval_1 = "08:40 - 09:20"
let result_1 = isInsideInterval(currentTime_1, timeInterval_1)

console.log(`* '${currentTime_1}' is ${result_1 ? "inside" : "not inside"} timeinterval '${timeInterval_1}'`)


/* ----- */

let currentTime_2 = "5:02"
let timeInterval_2 = "22:40 - 09:20"
let result_2 = isInsideInterval(currentTime_2, timeInterval_2)

console.log(`* '${currentTime_2}' is ${result_2 ? "inside" : "not inside"} timeinterval '${timeInterval_2}'`)

该函数的基础正常工作,但似乎缺少某种“模”运算-我不知道如何在给定以下参数的情况下实现对timeInterval的验证:

let currentTime = "5:02"
let timeInterval = "22:40 - 09:20"

1 个答案:

答案 0 :(得分:1)

让javascript帮助您-将时间解析为日期对象,如果'to'在'from'之前,则添加一天,然后只需使用<=>=

function parseTime(t) {
  var d = new Date();
  var time = t.match(/(\d+)(?::(\d\d))?\s*(p?)/);
  d.setHours(parseInt(time[1]) + (time[3] ? 12 : 0));
  d.setMinutes(parseInt(time[2]) || 0);
  return d;
}

function isInRange(t, range) {
  var tt = parseTime(t);
  var timeFrom = parseTime(range.split("-")[0])
  var timeTo = parseTime(range.split("-")[1])
  if (timeTo < timeFrom) timeTo.setDate(timeTo.getDate() + 1);

  return tt >= timeFrom && tt <= timeTo;
}

console.log(isInRange("11:00", "10:30 - 14:30"))
console.log(isInRange("18:00", "10:30 - 14:30"))
console.log(isInRange("22:15", "20:00 - 08:00"))

parseTime来自What is the best way to parse a time into a Date object from user input in Javascript?


为解决您有关如何处理to<from的特定问题,以上我使用了Date对象并添加了1天。在您的代码中,您将检查to<from是否将24小时添加到interval.endHour