Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the time closest to current time with 5 date objects javascript

I have the current time as currentTime.

And I have 5 date objects:

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

The time is 3:30 pm

Now, keeping in mind that a to e have successfully been turned into Date() objects.

How would I cycle through those 5, given the current time, to determine which time comes closest to the current time, but after it. So for instance I want to find in this case that d is the next time coming.

I'm just not sure of the way to do that.

like image 207
David G Avatar asked Jan 20 '26 12:01

David G


1 Answers

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

like image 52
Michael Geary Avatar answered Jan 22 '26 02:01

Michael Geary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!