Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How do i get the closest next date in an array of dates using moment js?

$
0
0

Ok i need to get the closest date (hours/minutes) in this array of dates, no matter how far the date is from the current day, say like right now is 13:55PM and this array has

[  11:41,  14:20,  15:30,  22:05,  23:16,]

so the closest one here is the 14:20, if the current time is 15:31, the next closest date from this new current time is the 22:05, no matter how far the date is (today), the next closest date is the next one, problem is, whenever i run this code, it keeps telling me the next one is 15:30, if the current time is 7:20 as an example, the next closest date is guess what, 15:30 :(

this is the code i'm running

  getFechaSiguiente() {    // Current time in millis    const now = +Moment(Moment().format('HH:mm'), 'HH:mm').format('x');    // Times in milliseconds    const timesInMillis = DataManager.ListaFechaCita.map(t => +Moment(t, 'HH:mm').format('x')); //times.map(t => +moment(t, "HH:mm").format("x"));    function closestTime(arr: any, time: any) {      return arr.reduce(function(prev: any, curr: any) {        return Math.abs(curr - time) < Math.abs(prev - time) ? curr : prev;      });    }    const closest = Moment(closestTime(timesInMillis, now)).format('HH:mm');    return closest;  }

let's pretend DataManager.ListaFechaCita is the array of dates


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>