gpt4 book ai didi

javascript - 将日期数组排序为最近的日期

转载 作者:行者123 更新时间:2023-11-29 17:37:44 29 4
gpt4 key购买 nike

我有一系列不同的日期。让我们说
const arr = ['21.可能','01。一月','05。二月','07。六月','20。 dec']

我想要按顺序排列日期,最接近今天的日期。所以在这种情况下(18.marts),输出应该是const arr = ['21.可能','07。六月','20。十二月','01。一月','05。二月']

如果不包括年份,这甚至可能吗?

最佳答案

如果你想按到今天的距离排序日期,最后出现过去的日期(负距离),你可以这样做:

const arr = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec'];

const today = new Date('2019/03/18'); // use new Date() for current day

arr.sort((a, b) => toDate(a) - toDate(b));

function toDate(str) {
const monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
const [day, monthName] = str.split(/\.\s*/);
const month = monthNames.indexOf(monthName.toLowerCase());
const date = new Date(today.getFullYear(), month, +day);
if (date < today) date.setFullYear(date.getFullYear() + 1);
return date;
}

console.log(arr); // ["21. may", "07. jun", "20. dec", "01. jan", "05. feb"]

关于javascript - 将日期数组排序为最近的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55229278/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com