我有一系列不同的日期。
可以说
const arr = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec']
我希望按日期排序,最接近今天的日期。因此,在这种情况下(18.集市),输出应为
const arr = ['21. may', '07. jun', '20. dec', '01. jan', '05. feb']
如果不包括年份,这是否有可能?
答案 0 :(得分:4)
如果要按到今天为止的距离排序日期,并且最后显示通过日期(负距离),则可以执行以下操作:
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"]
答案 1 :(得分:0)
如果您确定日期数据中没有年份,则可以尝试以下操作:
function sortDateStrArrayFrom(dayAndMonth, array) {
const dateFrom = new Date(dayAndMonth);
const datesBefore = [];
const datesEqual = [];
const datesAfter = [];
array.forEach(dateStr => {
const date = new Date(dateStr);
if (date < dateFrom) {
datesBefore.push(dateStr);
}
if (date === dateFrom) {
datesEqual.push(dateStr);
}
if (date > dateFrom) {
datesAfter.push(dateStr);
}
})
return [...datesEqual, ...datesAfter, ...datesBefore];
}
const arr = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec'];
sortDateStrArrayFrom('18. mar', arr); // ["21. may", "07. jun", "20. dec", "01. jan", "05. feb"]
如果需要,可以使用日期作为输入参数进行修改,也可以为每个日期设置相同的年份而与年份无关
答案 2 :(得分:0)
如果将字符串'2019'
添加到日期字符串的末尾,JavaScript的Date构造函数将把它解析为今年。一旦有了一堆Date对象,就很容易sort您的字符串,并使用findIndex获取将来的第一个对象:
const dates = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec'];
const sorted = [...dates].sort((a, b) => new Date(a) - new Date(b));
const soonest = sorted.findIndex(date => new Date(`${date} 2019`) > new Date());
const soonestDates = [...sorted.slice(soonest), ...sorted.slice(0, soonest)];
console.log(soonestDates); // ["21. may", "07. jun", "20. dec", "01. jan", "05. feb"]