How To Find The Closest Time To The Given Time Using Moment?
So I have a simple code, a working code, that get's the nearest time to the given time using moment. So what I wanted to do is to get the nearest time, before the given time but u
Solution 1:
Get rid of the Math.abs so you only get time before.
// Current time in millisconst now = +moment('10:16', 'HH:mm').format('x');
// List of timesconst times = ["10:00", "10:18", "23:30", "12:00"];
// Times in millisecondsconst timesInMillis = times.map(t => +moment(t, "HH:mm").format("x"));
functionclosestTime(arr, time) {
return arr.reduce(function(prev, curr) {
return (curr - time) < (prev - time) ? curr : prev;
});
}
const closest = moment(closestTime(timesInMillis, now)).format('HH:mm');
// closest is 10:18 but wanted to get 10:00console.log(closest);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Post a Comment for "How To Find The Closest Time To The Given Time Using Moment?"