首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >检查指定的时间是否以递增的时间表示。

检查指定的时间是否以递增的时间表示。
EN

Stack Overflow用户
提问于 2019-04-22 21:56:32
回答 2查看 52关注 0票数 0

以下是我拥有的一些变量:

代码语言:javascript
运行
复制
start time: 10:45
interval time: 5 (in minutes)
specific time: 14:20

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

例如,间隔时间为5。

代码语言:javascript
运行
复制
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分钟时,这是很困难的。因为:

代码语言:javascript
运行
复制
10:48
10:53
10:58
11:03
11:08
...

14:20在这篇文章中没有提到,所以它会记录"Not“。

如何才能确定从开始时间起,在递增的时间中是否提到了特定的时间?

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

我是,而不是,希望使用循环。必须有一个公式或函数可以帮助我实现这一点。谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-22 22:12:08

我认为您可以计算是否有可能对开始时间与指定时间和间隔之间的差异执行一个不稳定的除法。

根据时间间隔的比例,您可以以小时、分钟、秒、毫秒或基本上任何刻度来计算这个值。因为您的示例以分钟为单位处理,所以代码片段也是如此。

注意,这个片段假设两次都在同一天内(00:00 - 24:00),并且指定的时间在当天比开始时间晚。我会让你知道剩下的:)

代码语言:javascript
运行
复制
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');
}

票数 1
EN

Stack Overflow用户

发布于 2019-04-23 00:56:23

这项工作是通过以下方式进行的:

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

代码语言:javascript
运行
复制
// 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();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55801638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档