我正在尝试按出生日期对列表进行排序。当我使用此代码时,我会按月和日期按顺序获取所有日期。但我想在今天找到壁橱的生日。因此,接下来生日的人在顶部,在他处于底部的第二天。因为他有一年的生日接下来。
//what i am looking for
//("Person5", "April 09, 1992"));
//("Person2", "October 17, 1981"));
//("Person3", "December 25, 1961"));
//("Person4", "January 10, 1977"));
//("Person1", "February 04, 1967"));
function person(navn, fødselsdage, foto, alder) {
this.navn = navn;
this.fødselsdage = fødselsdage;
}
var contacts = [];
var p1 = contacts.push(new person("Person1", "February 04, 1967"));
var p2 = contacts.push(new person("Person2", "October 17, 1981"));
var p3 = contacts.push(new person("Person3", "December 25, 1961"));
var p4 = contacts.push(new person("Person4", "January 10, 1977"));
var p5 = contacts.push(new person("Person5", "April 09, 1992"));
sortByDateNoYear = function (adate, bdate) {
var results, lhdate = moment(adate.fødselsdage), rhdate = moment(bdate.fødselsdage);
results = lhdate.months() > rhdate.months() ? 1 : lhdate.months() < rhdate.months() ? -1 : 0;
if (results === 0) results = lhdate.date() > rhdate.date() ? 1 : lhdate.date() < rhdate.date() ? -1 : 0; return results;
}
contacts.sort(sortByDateNoYear);
contacts.sort(function (a, b) {
return new Date(a.fødselsdage).getDate() - new Date(b.fødselsdage).getDate()
&& new Date(a.fødselsdage).getMonth() - new Date(b.fødselsdage).getMonth()
});
for (var key in contacts) {
if (contacts.hasOwnProperty(key)) {
var obj = contacts[key];
document.write(obj["navn"] + " ");
document.write(obj["fødselsdage"] + "<br>");
}
}
答案 0 :(得分:1)
看看这个example。我删除了sortByDateNoYear
函数并更新了排序:
contacts.sort(function(a, b) {
let needSort = 0;
let today = moment()
.startOf('day');
let aBirthday = moment(a.fødselsdage, 'MMM DD, YYYY');
let bBirthday = moment(b.fødselsdage, 'MMM DD, YYYY');
let aNextBirthday = moment().month(aBirthday.month()).date(aBirthday.date());
let bNextBirthday = moment().month(bBirthday.month()).date(bBirthday.date());
if ((bNextBirthday.isAfter(today) && aNextBirthday.isAfter(today)) || (bNextBirthday.isBefore(today) && aNextBirthday.isBefore(today))){
needSort = bNextBirthday.isAfter(aNextBirthday)? -1: 1;
}
else {
needSort = bNextBirthday.isAfter(today)? 1: -1;
}
return needSort;
});
今天的输出将是:
Person5 April 9,1992
Person2 1981年10月17日
Person3 1961年12月25日
Person4 1977年1月10日
Person1 1967年2月4日