【问题标题】:JS: check if time doesn't exceed the maximum allowed from an array of intervalsJS:检查时间是否不超过间隔数组允许的最大值
【发布时间】:2021-09-21 11:40:45
【问题描述】:

目标是检查所选日期是否不超过最长时间。

我有一组时间间隔。最大时间为toMinutes - 20 minutes

您可以在下面找到我的解决方案,它总是返回false

如何编辑它以匹配预期结果,这也在下面指定?

const dateRanges = [{fromMinutes: 360, toMinutes: 600}, {fromMinutes: 700, toMinutes: 900}];
// "06:00 - 10:00", "11:40" - "15:00"

const minutesToHourFormat = (minutes) => {
  return new Date(minutes * 1000).toISOString().slice(14, 19);
};

const isWithinMinDate = () => {
  const selectedDate = "14:30";
  
  return dateRanges.every(({ toMinutes }) => {
     const minTime = minutesToHourFormat(toMinutes - 20);
      
     return selectedDate <= minTime;
  })
}

// Expected Result
// 14:30 -> true
// 14:40 -> false
// 14:10 -> true
// 9:50 -> false
// 9:30 -> true

console.log(isWithinMinDate(), 'res')

【问题讨论】:

  • 我不明白你想要什么。 “最大时间”的定义将是多个,因为您有多个toMinutes,您是否要检查给定时间是否晚于 最早 toMinutes 之前的 20 分钟?那么你得到true是正常的。请准确解释您想到的逻辑......
  • 我已经添加了预期结果。我需要检查 selectedValue 是否不超过两个 toMinutes
  • 我不认为你的逻辑会起作用,你正在做 toMinutes * 1000 ,在你的情况下是 360*1000 并将它作为新日期的参数传递,它需要时间戳。在您的情况下, new Date() 将始终返回 1970 年的某个日期。
  • 你能解释一下 360 分钟是什么意思吗?从午夜开始已经过去了 360 分钟?如果是,那么我会用相同的逻辑将 14:30 转换为分钟,然后比较数字
  • 我不明白。当 toMinutes 值为 15:00 时,为什么 14:30 应该返回 false?那是20多分钟。如果这是预期的,那么为什么 14:10 应该返回 true,因为它距离 15:00 也有 20 多分钟的路程。

标签: javascript date time


【解决方案1】:

您的every 调用应验证这两个限制,因为给定时间可能在任何间隔之外,或者当它在一个结束间隔的 20 分钟内时,在检查时仍会考虑反对以后的间隔!

我更愿意将选定的时间字符串转换为分钟,而不是相反:

const hourFormatToMinutes = (fmt) =>
    fmt.split(":").reduce((h, m) => h * 60 + +m);

const minutesToHourFormat = (minutes) => 
    new Date(minutes * 1000).toISOString().slice(14, 19);

const dateRanges = [
    { fromMinutes: hourFormatToMinutes("6:00"), toMinutes: hourFormatToMinutes("10:00") }, 
    { fromMinutes: hourFormatToMinutes("11:40"), toMinutes: hourFormatToMinutes("15:00") }
];

const isWithinMinDate = (hourFmt) => {
    const minutes = hourFormatToMinutes(hourFmt);
    return dateRanges.some(({ fromMinutes, toMinutes }) =>
        minutes >= fromMinutes && minutes < toMinutes - 20
    );
}

for (const test of ["14:30", "14:40", "14:10", "9:50", "9:30"]) {
    console.log(test, isWithinMinDate(test));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    相关资源
    最近更新 更多