如果我有一个未来日期对象的未排序数组,那么选择最接近用户下一个生日的日期的最佳方法是什么?例如,
const dates = [new Date(2023, 12, 23),
new Date(2023, 12, 2),
new Date(2023, 12, 6),
new Date(2023, 10, 23),
new Date(2023, 9, 10),
new Date(2023, 8, 1),
new Date(2023, 7, 4),
new Date(2023, 7, 7),
new Date(2023, 1, 1)]
findClosestDate(new Date(1995, 10, 3)); // should return dates[3]
发布于 2022-09-09 21:28:47
function findClosestDate(date) {
const today = new Date()
const nextDate = new Date(date)
nextDate.setFullYear(today.getFullYear())
if (nextDate < today) {
nextDate.setFullYear(today.getFullYear() + 1)
}
console.log(nextDate)
const dates = [
new Date(2023, 12, 23),
new Date(2023, 12, 2),
new Date(2023, 12, 6),
new Date(2023, 10, 23),
new Date(2023, 9, 10),
new Date(2023, 8, 1),
new Date(2023, 7, 4),
new Date(2023, 7, 7),
new Date(2023, 1, 1)
]
// calculate distance to each date
const diffs = dates.map(d => Math.abs(nextDate - d))
// find the lowest
const best = Math.min(...diffs)
// get the index of the lowest
const bestIndex = diffs.indexOf(best)
// return the best one
return dates[bestIndex]
}
const result = findClosestDate(new Date(1995, 10, 3));
console.log(result)
发布于 2022-09-10 05:51:46
正如许多评论已经指出的那样,这个问题似乎有一些不确定因素或错误。我现在正试图以我理解OP的意图来回答这个问题:“在建议的日期中,哪一天最接近同一年的某一生日?”另外,我假设OP不知道new Date()
中的月份计数器在JavaScript中是零的。因此,我手动调整了所有日期。
const dates = [
new Date(2023, 11, 23),
new Date(2023, 11, 2),
new Date(2023, 11, 6),
new Date(2023, 9, 23),
new Date(2023, 8, 10),
new Date(2023, 7, 1),
new Date(2023, 6, 4),
new Date(2023, 6, 7),
new Date(2023, 0, 1)
], bd=new Date(1995, 9, 3); // 3 October 1995
// future birthday;
const fbd=new Date(dates[0].getFullYear(),bd.getMonth(),bd.getDate());
const closest=dates.reduce((a,c)=>Math.abs(c-fbd)<Math.abs(a-fbd)?c:a);
console.log(closest.toLocaleString());
https://stackoverflow.com/questions/73667607
复制相似问题