Home > Software engineering >  How to get the n umber of days left until a specific day
How to get the n umber of days left until a specific day

Time:09-19

How can I get the number of days left until next birthday from this array of objects?

const people = [
    { name: 'Bill', dob: new Date('07/11/1949') },
    { name: 'Will', dob: new Date('02/21/1979') }
]

So basically I need how many days there are from today until the birth date.

I tried to extract the month and day from the dob like this:

for (let i = 0; i < people.length; i  ) {
    const personDob = people[i].dob
    const personBirthMonth = new Date(personDob).getMonth()   1
    const personDayOfBirth = new Date(personDob).getUTCDate()  1
}

I've checked this post but I'm kind of confused because I don't need to compare the full year, only the months and days I guess.

I'm not sure how to get the remaining days left.

CodePudding user response:

Do you mean this?

If the date is past, then plus one year on the year of now.

Just a simple example, please modify yourself.

So code:

const now = new Date(),
    date = new Date("07/11/1949");

if (now.getMonth() > date.getMonth() || (now.getMonth() == date.getMonth() && now.getDate() > date.getDate()))
    date.setFullYear(now.getFullYear()   1);
const days = (date.getTime() - now.getTime()) / 86400000;
console.log(days   " days left.");

CodePudding user response:

May you could try to extract like this

currDate = new Date()
people.forEach((person)=>{
     let nextbd = person.dob;
     nextbd.setFullYear(currDate.getFullYear()   1);
     let diffTime = Math.abs(nextbd  - currDate);
     let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 

   console.log(person.name " has next birdthday after "  diffDays  " days");
     
})

CodePudding user response:

So you basically want to know the days remaining till the birthday of a person.

Let's say someone has a birthday on 21 September 2022, the code for such will go like this. Also, feel free to fix it according to your situation.

 function getNumberOfDays(today, birthday) {
        const date1 = new Date(today);
        const date2 = new Date(birthday);
    
        // One day in milliseconds
        const oneDay = 1000 * 60 * 60 * 24;
    
        // Calculating the time difference between two dates
        const diffInTime = date2.getTime() - date1.getTime();
    
        // Calculating the no. of days between two dates
        const diffInDays = Math.round(diffInTime / oneDay);
    
        return diffInDays;
    }
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth()   1).padStart(2, '0');
    var yyyy = today.getFullYear();
    console.log(getNumberOfDays(`${mm}/${dd}/${yyyy}`,"9/21/2022", ));

  • Related