Calculate days remaining until next birthday in Javascript
datetime, javascript
Solution
I'd do something like this:
var myBirthday, today, bday, diff, days;
myBirthday = [6,2]; // 6th of February
today = new Date();
bday = new Date(today.getFullYear(),myBirthday[1]-1,myBirthday[0]);
if( today.getTime() > bday.getTime()) {
bday.setFullYear(bday.getFullYear()+1);
}
diff = bday.getTime()-today.getTime();
days = Math.floor(diff/(1000*60*60*24));
alert(days+" days until Niet's birthday!");
Problem
I'm trying to calculate remaining days until the next birthday but keeps running into problems. This is the code so far (has some issues with negative days if your birthday has already been this year etc). Any tips on how I can solve this? ``` var birthdayDate = new Date(year, month-1, day, 12); var now = new Date(); var days = 0; Math.floor(days = ( (birthdayDate.getTime() - now.getTime()) / (1000*60*60*24))); if(days < 0) { var yearDiff = birthdayDate.getYear() - now.getYear(); yearDiff *= -1; var monthDiff = birthdayDate.getMonth() - now.getMonth(); var daysDiff = birthdayDate.getDay() - now.getDay(); if(monthDiff <= 0) { if(daysDiff > 0) { } else { days += 365; } } var extraDays = yearDiff / 4; days = days + (yearDiff * 365) + extraDays; } else { throw new FutureDateException(); } days = Math.floor(Math.round(days)); if(days === 365) { days = 0; } if(days === 366) { days = 1; } return days; ```