【发布时间】:2021-06-22 11:23:54
【问题描述】:
好的,我需要在这个日期数组中获取最接近的日期(小时/分钟),无论日期离当天有多远,比如现在是下午 13:55,这个数组有
[
11:41,
14:20,
15:30,
22:05,
23:16,
]
所以这里最接近的是 14:20,如果当前时间是 15:31,那么距离这个新的当前时间的下一个最接近的日期是 22:05,无论日期有多远(今天),下一个最接近的日期是下一个,问题是,每当我运行此代码时,它一直告诉我下一个是 15:30,例如,如果当前时间是 7:20,下一个最接近的日期是猜猜看,15 :30 :(
这是我正在运行的代码
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;
}
让我们假设 DataManager.ListaFechaCita 是日期数组
【问题讨论】:
标签: javascript typescript react-native date momentjs