【问题标题】:Find the time closest to current time with 5 date objects javascript使用 5 个日期对象 javascript 查找最接近当前时间的时间
【发布时间】:2013-07-15 22:01:42
【问题描述】:

我将当前时间设为 currentTime。

我有 5 个日期对象:

a = 凌晨 2:20 b = 凌晨 2 点 40 分 c = 凌晨 3:00 d = 下午 4:00 e = 下午 6:00

时间是下午 3:30

现在,请记住 a 到 e 已成功转换为 Date() 对象。

在给定当前时间的情况下,我将如何循环遍历这 5 个时间,以确定哪个时间最接近当前时间,但在它之后。因此,例如,我想在这种情况下找到 d 是下一次来。

我只是不确定如何做到这一点。

【问题讨论】:

  • 使用for 循环遍历它们。从目标日期减去日期,得到绝对值。跟踪最接近的 - 如果当前迭代的日期更接近,则存储它,否则继续。
  • Date 对象仅代表完整的日期和时间。不只是一次。你是说每天都有时间吗?那么如果时间是晚上 7:00,我应该在第二天凌晨 2:20 得到吗?还是返回null?
  • @Ian - 几乎正确,但不是绝对值。 OP 想要最近的时间大于当前时间。所以丢弃减法产生的负值,只看正值。
  • @MichaelGeary 哎呀,我没看到, but after it. :) 你是对的!

标签: javascript date time


【解决方案1】:
// Given an array of Date objects and a start date,
// return the entry from the array nearest to the
// start date but greater than it.
// Return undefined if no such date is found.
function nextDate( startDate, dates ) {
    var startTime = +startDate;
    var nearestDate, nearestDiff = Infinity;
    for( var i = 0, n = dates.length;  i < n;  ++i ) {
        var diff = +dates[i] - startTime;
        if( diff > 0  &&  diff < nearestDiff ) {
            nearestDiff = diff;
            nearestDate = dates[i];
        }
    }
    return nearestDate;
}

var testDates = [
    new Date( 2013, 6, 15, 16, 30 ),
    new Date( 2013, 6, 15, 16, 45 ),
    new Date( 2013, 6, 15, 16, 15 )
];

console.log( nextDate( new Date( 2013, 6, 15, 16, 20 ), testDates ) );
console.log( nextDate( new Date( 2013, 6, 15, 16, 35 ), testDates ) );

    console.log( nextDate( new Date( 2013, 6, 15, 16, 50 ), testDates ) );

【讨论】:

    【解决方案2】:

    可能有一种更简洁/更快的方法来做到这一点,但我会制作第二个数组,其中包含 a 到 e 的值和 currentTime 之间的差异,然后将第二个数组用于sort 第一个数组(取两个值的差异的差异)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多