检查是否以递增的时间提到指定的时间

问题描述 投票:0回答:2

以下是我的一些变量:

start time: 10:45
interval time: 5 (in minutes)
specific time: 14:20

我需要找出特定时间是否准确地落在从开始时间开始递增的任何时间。

例如,间隔时间为5。

10:45 incremented by interval time
11:00
11:05
11:10
...
14:20 << specific time found

if(specificTime is mentioned in any of the incremented times) {
    console.log('Found it!');
} else {
    console.log('Not found');
}

但是当开始时间是10:48并且间隔时间是5分钟时,这很难。因为:

10:48
10:53
10:58
11:03
11:08
...

并且在这个中没有提到14:20,所以它会记录“Not found”。

如何确定从开始时间开始递增的时间内是否提到了特定时间?

间隔时间不总是5,其他变量也是动态的。

我不打算使用循环。必须有一个公式或功能可以帮助我实现这一目标。谢谢!

javascript jquery datetime math
2个回答
1
投票

我认为您可以计算是否可以对开始时间与指定时间和间隔之间的差异进行不间断的划分。

根据您的时间间隔的比例,您可以以小时,分钟,秒,毫秒或基本上任何比例计算。由于您的示例只需几分钟即可完成,因此代码段也可以。

请注意,此代码段假定两个时间都在同一天(00:00 - 24:00),并且特定时间在该天之后的时间晚于开始时间。我会让你弄清楚剩下的:)

function toMinutes(hours, minutes) {
  return (hours * 60) + minutes;
}

const startTime = toMinutes(10, 45);
const specificTime = toMinutes(14, 20);
const interval = toMinutes(0, 5);

const difference = specificTime - startTime;

if (difference % interval === 0) {
  console.info('Found it!');
  console.info('Minutes:', difference);
  console.info('Intervals:', difference / interval);
} else {
  console.error('Not found');
}

0
投票

这适用于: - 将时间字符串转换为数字分钟(使用countOfMinutes()) - 从startTime中减去specificTime(如果我们增加到12:00,则进行调整) - 将结果除以minsPerIncrement并检查余数是否为零

// The big payoff -- calculates whether we exactly hit `specificTime`
function isExact(start, specific, increment){
  let difference = countOfMinutes(specific) - countOfMinutes(start);
  if(difference <= 0){ difference += 12 * 60; } // Add 12 hours if necessary
  return difference % increment == 0;
}

// The converter -- because numbers are easier to divide than strings
function countOfMinutes(timeString){
  const hours = timeString.slice(0, timeString.indexOf(":"));
  const mins = timeString.slice(timeString.indexOf(":") + 1);
  return hours * 60 + mins;
}

// The results -- some readable output
function report(){
  console.log(`
     Repeatedly adding ${minsPerIncrement} to ${startTime} will eventually yield ${specificTime}?:
     _ ${isExact(startTime, specificTime, minsPerIncrement)} _`);
}

// The pudding -- a couple of test cases
let start, specific, minsPerIncrement;

startTime = "12:30"; specificTime = "3:55"; minsPerIncrement = 21;
report();

startTime = "4:20"; specificTime = "11:45"; minsPerIncrement = 5;
report();

startTime = "11:45"; specificTime = "4:20"; minsPerIncrement = 5;
report();
© www.soinside.com 2019 - 2024. All rights reserved.