以下是我拥有的一些变量:
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“。
如何才能确定从开始时间起,在递增的时间中是否提到了特定的时间?
间隔时间并不总是5,其他变量也是动态的。
我是,而不是,希望使用循环。必须有一个公式或函数可以帮助我实现这一点。谢谢!
发布于 2019-04-22 22:12:08
我认为您可以计算是否有可能对开始时间与指定时间和间隔之间的差异执行一个不稳定的除法。
根据时间间隔的比例,您可以以小时、分钟、秒、毫秒或基本上任何刻度来计算这个值。因为您的示例以分钟为单位处理,所以代码片段也是如此。
注意,这个片段假设两次都在同一天内(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');
}
发布于 2019-04-23 00:56:23
这项工作是通过以下方式进行的:
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();
https://stackoverflow.com/questions/55801638
复制相似问题