-1

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.

Tom
  • 53
  • 1
  • 10
  • 1
    Hint: You probably want to compare the current date to the birthday in this year or the next year. – some-user Sep 19 '22 at 12:19
  • so where do you want to save or put the days till birthday ? In the same object as another attribute besides `name` and `dob` ? – ThS Sep 19 '22 at 12:43
  • Does this answer your question? [How to calculate number of days between two dates?](https://stackoverflow.com/questions/542938/how-to-calculate-number-of-days-between-two-dates) – Michael M. Sep 19 '22 at 13:00

2 Answers2

1

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.");
Chang Alex
  • 505
  • 3
  • 11
0

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");
     
})
Jaydip Jadhav
  • 12,179
  • 6
  • 24
  • 40