如何根据当前日期从数组中找到最接近的日期值?

时间:2018-06-30 06:00:30

标签: javascript arrays sorting date

我想根据当前日期获取此数组上的下一个最接近的日期。

var dates = [
    'Aug 18, 2018 03:24:00',
    'August 19, 2018 03:24:00',
    'September 17, 2018 03:24:00',
    'September 14, 2018 03:24:00',
    'August 18, 2018 03:24:00',
    'July 16, 2018 03:24:00',
    'July 15, 2018 03:24:00',
    'December 15, 2018 03:24:00',
    'July 13, 2018 03:24:00',
];

    var now = new Date();

4 个答案:

答案 0 :(得分:1)

首先,您需要将每个日期转换为时间戳,然后将每个日期减去当前日期,并将时间戳差异存储在temp数组中,然后获取最小值的索引,并使用该索引来访问日期中最接近的日期原始数组。

var dates = [
    'July 16, 1995 03:24:00',
    'Aug 18, 1995 03:24:00',
    'August 19, 1995 03:24:00',
    'September 17, 1995 03:24:00',
    'September 14, 1995 03:24:00',
    'August 18, 1995 03:24:00',
    'July 16, 1995 03:24:00',
    'December 15, 1995 03:24:00',
    'July 13, 1995 03:24:00',
]

var temp = dates.map(d => Math.abs(new Date() - new Date(d).getTime()));
var idx = temp.indexOf(Math.min(...temp));
console.log(dates[idx]);

答案 1 :(得分:0)

有关更多信息,请参见Array.prototype.reduce()

// Input.
const dates = ['July 16, 1995 03:24:00','Aug 18, 1995 03:24:00','August 19, 1995 03:24:00','September 17, 1995 03:24:00','September 14, 1995 03:24:00','August 18, 1995 03:24:00','July 16, 1995 03:24:00','December 15, 1995 03:24:00','July 13, 1995 03:24:00']

// Closest Date.
const closestDate = dates => dates.reduce((x, date) => {
  const distance = Math.abs(Date.now() - new Date(date))
  if (!x.distance || distance < x.distance) return {distance, date}
  return x
}, {}).date

// Output + Proof.
const output = closestDate(dates)
console.log(output)

答案 2 :(得分:0)

您可以使用moment.js库将日期转换为所需的任何格式。 您只需在数组上mapping并使用
 moment( yourDate )。format(您的格式)功能。

以下是一项可以帮助您的小功能:
它有2个参数->

  • a) 日期 ->这是您的日期数组&&
  • b) 目标 ,即您要与之进行比较的值。

const dates = [
                '1980-7-12',
                '2001-1-5',
                '2018-4-12',
                '1999-3-25'
            ];   

    const nearestDate = (dates, target) => {
          if (!target

) target = Date.now()
      else if (target instanceof Date) target = target.getTime()

      let nearest = Infinity
      let winner = -1

      dates.forEach(function (date, index) {
        if (date instanceof Date) date = date.getTime()
        let distance = Math.abs(date - target)
        if (distance < nearest) {
          nearest = distance
          winner = index
        }
      })

      return winner
    }

答案 3 :(得分:0)

您可以按当前日期之间的绝对差对dates数组进行排序,然后提取第一项:

var dates = [
    'Aug 18, 2018 03:24:00',
    'August 19, 2018 03:24:00',
    'September 17, 2018 03:24:00',
    'September 14, 2018 03:24:00',
    'August 18, 2018 03:24:00',
    'July 16, 2018 03:24:00',
    'July 15, 2018 03:24:00',
    'December 15, 2018 03:24:00',
    'July 13, 2018 03:24:00',
];

var now = new Date();

var [ closest ] = dates.sort((a,b) => {

  const [aDate, bDate] = [a,b].map(d => Math.abs(new Date(d) - now));

  return aDate - bDate;

});

console.log(closest);