3

私は currentTime として現在の時刻を持っています。

そして、私は5つの日付オブジェクトを持っています:

a = 午前 2:20 b = 午前 2:40 c = 午前 3:00 d = 午後 4:00 e = 午後 6:00

時間は午後3時30分

ここで、a から e が正常に Date() オブジェクトに変換されたことを覚えておいてください。

現在の時刻が与えられた場合、どの時刻が現在の時刻に最も近いかを判断するために、これらの 5 つをどのように循環させますか。たとえば、この場合、 d が次回来ることを見つけたいと思います。

私はそれを行う方法がわかりません。

4

2 に答える 2

9
// 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 ) );

于 2013-07-15T23:35:51.047 に答える
0

よりきちんとした/より高速な方法があるかもしれませんが、a から e の値と currentTime の差を含む 2 番目の配列を作成し、この 2 番目の配列をsort最初の配列に使用します (次の diff の diff を取得します)。両方の値)。

于 2013-07-15T22:05:31.730 に答える