Anandeva
Anandeva

Reputation: 162

How can i get the nearest next time in array using moment?

I want to find the nearest next time to a given time, I got this code from stack overflow but I am unable to get the desired result

// Current time in millis
const now = +moment('10:07', 'HH:mm').format('x');
// List of times
const times = ["10:00", "10:18", "23:30", "12:00"];
// Times in milliseconds
const timesInMillis = times.map(t => +moment(t, "HH:mm").format("x"));

function closestTime(arr, time) {
  return arr.reduce(function(prev, curr) {
    return Math.abs(curr - time) < Math.abs(prev - time) ? curr : prev;
  });
}

const closest = moment(closestTime(timesInMillis, now)).format('HH:mm');

// closest is 10:00 but i want the next time 10:18
console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Upvotes: 1

Views: 187

Answers (1)

mplungjan
mplungjan

Reputation: 177702

No need for moment at all

24-hour time is sortable and directly comparable

const times = ["10:00", "10:18", "23:30", "12:00"].sort();

const getClosest = targetTime => times.find(time => time >= targetTime) || "N/A";

console.log(getClosest("10:07"));

console.log(getClosest("11:30"));

console.log(getClosest("13:30"));

console.log(getClosest("23:40")); // not available in array

Upvotes: 3

Related Questions