1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="utf-8"> 6 <title></title> 7 </head> 8 9 <body> 10 <h1></h1> 11 </body> 12 13 </html> 14 <script language=javascript> 15 function getAge(strAge) { 16 const birArr = strAge.split("-"); 17 const birYear = Number(birArr[0]); 18 const birMonth = Number(birArr[1]); 19 const birDay = Number(birArr[2]); 20 21 const today = new Date(); 22 const nowYear = today.getFullYear(); 23 const nowMonth = today.getMonth() + 1; //记得加1 24 const nowDay = today.getDate(); 25 let returnAge; 26 27 if (birArr === null) { 28 return false 29 }; 30 const d = new Date(birYear, birMonth - 1, birDay); 31 console.log(d.getFullYear(), birYear, (d.getMonth() + 1), birMonth, d.getDate(), birDay); 32 if (d.getFullYear() === birYear && (d.getMonth() + 1) === birMonth && d.getDate() === birDay) { 33 if (nowYear === birYear) { 34 returnAge = 0; // 35 } else { 36 let ageDiff = nowYear - birYear; // 37 if (ageDiff > 0) { 38 if (nowMonth === birMonth) { 39 let dayDiff = nowDay - birDay; // 40 if (dayDiff < 0) { 41 returnAge = ageDiff - 1; 42 } else { 43 returnAge = ageDiff; 44 } 45 } else { 46 let monthDiff = nowMonth - birMonth; // 47 if (monthDiff < 0) { 48 returnAge = ageDiff - 1; 49 } else { 50 returnAge = ageDiff; 51 } 52 } 53 } else { 54 return "出生日期晚于今天,数据有误"; //返回-1 表示出生日期输入错误 晚于今天 55 } 56 } 57 return returnAge; 58 } else { 59 return ("输入的日期格式错误!"); 60 } 61 } 62 const age = getAge("2021-07-05") 63 console.log(age); 64 document.getElementsByTagName('h1')[0].innerHTML = age 65 </script>
参考
https://blog.csdn.net/u013746071/article/details/90903997