使用5个日期对象javascript查找最接近当前时间的时间

Dav*_*d G 3 javascript time date

我将当前时间作为currentTime.

我有5个日期对象:

a = 2:20 am b = 2:40 am c = 3:00 am d = 4:00 pm e = 6:00 pm

时间是下午3:30

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

在给定当前时间的情况下,我如何循环通过那些5来确定哪个时间最接近当前时间,但是在它之后.所以例如我想在这种情况下找到d是下一次来的.

我只是不确定这样做的方法.

Mic*_*ary 8

// 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 ) );
Run Code Online (Sandbox Code Playgroud)

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