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