Search code examples
javascripthtmlphonegap

who has birthday next?


I am trying to sort a list with birth dates. When I use this code i get all dates in order by months and days. But I want to find the closet birthday by today. So the person who has birthday next is in the top, and the day after he is in the bottom. Because of there is a year to he has birthday next.

//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>");
    }
}

Solution

  • Take a look this example. I removed sortByDateNoYear function and updated sorting:

    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;
    });
    

    For today the output will be:

    Person5 April 09, 1992

    Person2 October 17, 1981

    Person3 December 25, 1961

    Person4 January 10, 1977

    Person1 February 04, 1967