1. How many days are before birthday:
<! DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> < title> Document </ title> </ head> <body> <script> // Given the month and date of the birthday, calculate how many days have passed the birthday function getDaysToBirthday (month, day) { var nowTime = new Date (); var thisYear = nowTime.getFullYear (); // this year's birthday var birthday = new Date (thisYear, month-1 , day);// This year's birthday has passed, then calculate the number of days until next birthday if (birthday < nowTime) { birthday.setFullYear(nowTime.getFullYear() + 1); } var timeDec = birthday - nowTime; var days = timeDec / (24 * 60 * 60 * 1000); return Math.ceil(days); } getDaysToBirthday(11, 2); </script> </body> </html>
2. Calculate the age based on the date of birth:
<! DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> < title> Document </ title> </ head> <body> <script> // Whether the leap year function isLeap (year) { return (year% 4 === 0 && year% 100! == 0) || (year% 400 === 0 ); } // Calculate the age based on the date of birth function getAge (year, month, day) { // Get the current date var nowTime = new Date ();var age = nowTime.getFullYear ()-year; // roughly calculate the age // If the birthday is February 29 and this year is not a leap year, the birthday of this year is calculated on the 28th if (month === 2 && day === 29 &&! IsLeap (nowTime.getFullYear ())) { day = 28 ; } // Get this year ’s birthday var nowBirthday = new Date (nowTime.getFullYear (), month-1 , day); console.log (nowBirthday, nowTime); if (nowBirthday> nowTime) { // if this year ’s If you have n’t had a birthday, you will lose one year age-- ; } return age; } console.log (getAge ( 2000, 2, 29 )); </ script> </ body> </html>