教程 date-fns tutorial

closestIndexTo

返回与指定日期数组中的某个日期最接近的日期的索引。

javascript
import { closestIndexTo } from "date-fns";

// 示例日期数组
const dates = [
  new Date(2024, 0, 1), // 2024年1月1日
  new Date(2024, 2, 15), // 2024年3月15日
  new Date(2024, 4, 30), // 2024年5月30日
  new Date(2024, 7, 10), // 2024年8月10日
];

// 指定日期
const targetDate = new Date(2024, 5, 1); // 2024年6月1日

// 查找最接近的日期索引
const closestIndex = closestIndexTo(targetDate, dates);

console.log(`与指定日期最接近的日期索引为:${closestIndex}`);