ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

js 根据出生日期年月日 计算年龄

2021-07-07 10:00:50  阅读:340  来源: 互联网

标签:ageDiff const birMonth js else 出生日期 年月日 birYear returnAge


 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

标签:ageDiff,const,birMonth,js,else,出生日期,年月日,birYear,returnAge
来源: https://www.cnblogs.com/-roc/p/14980156.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有