How does javascript calculate the age
This article mainly introduces how to calculate the age of javascript, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Javascript calculates the age by: (1) obtaining the year, month and day of birth respectively; (2) obtaining the year, month and day of the current time respectively; (3) subtracting from each other to obtain the difference between years, days and months; (4) calculating the age through the differences between years, months and days.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
Javascript's method of calculating age
Function jsGetAge (strBirthday) {var returnAge; / / calculate age based on birthday / / the following five lines are used to obtain the date of birth. If you get it from your ID card, you need to change var strBirthdayArr=strBirthday.split slightly ("-"); var birthYear = strBirthdayArr [0]; var birthMonth = strBirthdayArr [1]; var birthDay = strBirthdayArr [2]; d = new Date (); var nowYear = d.getFullYear (); var nowMonth = d.getMonth () + 1 Var nowDay = d.getDate (); if (nowYear = = birthYear) {returnAge = 0 birthYear / 0 in the same year} else {var ageDiff = nowYear-birthYear; / / year difference if (ageDiff > 0) {if (nowMonth = = birthMonth) {var dayDiff = nowDay-birthDay;// day difference if (dayDiff < 0) {returnAge = ageDiff-1 } else {returnAge = ageDiff;}} else {var monthDiff = nowMonth-birthMonth;// month difference if (monthDiff < 0) {returnAge = ageDiff-1;} else {returnAge = ageDiff } else {returnAge =-1Placement / return-1 indicates that the date of birth was entered incorrectly later than today} return returnAge;// returns the one-year age}
Call the jsGetAge () function with a birthday of 1995-09-15
Console.log (jsGetAge (1995-09-15))
The age is:
twenty-six
If the birthday is 1995-09-25
Console.log (jsGetAge (1995-09-25))
The age is:
25 Thank you for reading this article carefully. I hope the article "how to calculate the Age of javascript" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!