【问题标题】:How do i get the closest next date in an array of dates using moment js?如何使用矩 js 在日期数组中获取最接近的下一个日期?
【发布时间】: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


    【解决方案1】:

    您可以按给定值之间的时间差对数组进行排序并选择第一个元素:

    例如:

    a = [10,20,30,40,50]
    b = 18
    c = a.sort((x1,x2)=> Math.abs(x1-b) - Math.abs(x2-b) )[0] //20
    

    同样的操作也适用于 momentjs 对象:

    a = [moment('10:30','HH:mm'), 
         moment('11:30','HH:mm'), 
         moment('15:30','HH:mm')]
    b = moment('12:00','HH:mm')
    c = a.sort((x1,x2)=> Math.abs(x1-b) - Math.abs(x2-b) )[0] // 11:30
    

    【讨论】:

    • 不错,但这个想法是,只要时间已经超过数组中的前一个时间,就必须进入下一个最近的小时
    • 那样的话就更简单了:
    【解决方案2】:

    您可以使用 time 数组中的 time 值获取您的时间增量,然后返回正值。

    const times = [ '11: 41', '14: 20', '15: 30', '22: 05', '23: 16'];
    const compareTime = moment('15:31', 'hh:mm');
    const closestTime = times.find((time) => {
      const diff = moment(time, 'hh:mm').diff(compareTime, 'minutes');
      return diff >= 0;
    });
    console.log(closestTime);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"&gt;&lt;/script&gt;

    【讨论】:

    • 我在 jsfiddle 上测试了您的代码,但是当我将您的 13:55 更改为 15:55 时,下一个最近的时间显示为 15:30 而不是 22:05
    • 它正在返回具有最小增量的时间。您想要下一个最近的时间吗?
    • 请检查更新后的代码。我假设您的 times 数组已排序。
    • 它有效,迄今为止最好的解决方案,我正在检查你的答案
    猜你喜欢
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2022-01-24
    • 2019-05-22
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多