JavaScript 计算年龄
JavaScript提供了一些内置的日期和时间函数,可以帮助计算年龄(出生日期)。使用这些JavaScript方法,您可以轻松找到任何人的年龄。为此,我们需要从用户那里获取一个日期输入和当前系统日期。在计算它们之间的差异时,我们需要考虑以下条件:
- 如果 当前日期 小于用户输入的日期(出生日期),那个月份将不会作为已完成的月份计算在内。否则,我们将在当前日期上加上月份的天数(30或31),以得到它们之间的差异。
- 如果 当前月份 小于出生月份,将不会计算当前年份。为了得到月份的差异,我们将通过向当前月份添加总月数(12)来进行减法运算。
- 最后,在满足上述两个条件之后,我们只需要减去日期、月份和年份。
现在,我们将把这个过程转化为实际的实现。
有多种方法可以根据出生日期计算年龄。我们将讨论一些简单易懂的方法,使用JavaScript进行年龄计算。
示例1:预设的日期输入
在这个示例中,我们在代码中提供了一个日期(出生日期),而不是从用户那里获取输入。
<script>
var dob = new Date("06/24/2008");
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
document.write("Age of the date entered: " + age + " years");
</script>
输出
Age of the date entered: 12 years
示例2:动态日期输入
在此示例中,我们将创建一个HTML表单,从用户那里接收日期输入,然后使用JavaScript计算年龄。它将从用户那里动态接收输入。这个HTML表单将使用日历来选择日期输入。
<html>
<head>
<script>
function ageCalculator() {
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
if(userinput==null || userinput=='') {
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
} else {
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
return document.getElementById("result").innerHTML =
"Age is: " + age + " years. ";
}
}
</script>
</head>
<body>
<center>
<h2 style="color: 32A80F" align="center"> Calculate Age from Date of Birth <br> <br> </h2>
<!-- Choose a date and enter in input field -->
<b> Enter Date of Birth: <input type=date id = DOB> </b>
<span id = "message" style="color:red"> </span> <br><br>
<!-- Choose a date and enter in input field -->
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br><br>
<h3 style="color:32A80F" id="result" align="center"></h3>
</center>
</body>
</html>
输出
通过执行上面的代码,将出现一个HTML表单。在这里,从日历中选择一个日期(出生日期),然后点击 计算年龄 按钮,以计算提供的出生日期的年龄。
如果你选择一个日期然后点击计算年龄,会出现错误。
注意:在测试这个程序时,请记住日期应该小于当前系统日期。
在这个屏幕截图中,您可以看到我们在输入框中提供了一个日期 12-06-2012 ,计算出年龄后得到 8年 。
重要说明:
请注意,我们仅计算年龄,如8年、9年,而不是像8年5个月23天这样。因此,我们现在将进行详细计算。
示例3:按年、月、日计算年龄
此示例将按年、月、日计算和显示年龄,而不仅仅是年份。 例如, 对于出生日期为2015年12月27日的人,年龄为4年9个月23天。
复制代码
<html>
<head>
<script>
function ageCalculator() {
//collect input from HTML form and convert into date format
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
//check user provide input or not
if(userinput==null || userinput==''){
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
}
//execute if the user entered a date
else {
//extract the year, month, and date from user date input
var dobYear = dob.getYear();
var dobMonth = dob.getMonth();
var dobDate = dob.getDate();
//get the current date from the system
var now = new Date();
//extract the year, month, and date from current date
var currentYear = now.getYear();
var currentMonth = now.getMonth();
var currentDate = now.getDate();
//declare a variable to collect the age in year, month, and days
var age = {};
var ageString = "";
//get years
yearAge = currentYear - dobYear;
//get months
if (currentMonth >= dobMonth)
//get months when current month is greater
var monthAge = currentMonth - dobMonth;
else {
yearAge--;
var monthAge = 12 + currentMonth - dobMonth;
}
//get days
if (currentDate >= dobDate)
//get days when the current date is greater
var dateAge = currentDate - dobDate;
else {
monthAge--;
var dateAge = 31 + currentDate - dobDate;
if (monthAge < 0) {
monthAge = 11;
yearAge--;
}
}
//group the age in a single variable
age = {
years: yearAge,
months: monthAge,
days: dateAge
};
if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
ageString = age.years + " years, " + age.months + " months, and " + age.days + " days old.";
else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) )
ageString = "Only " + age.days + " days old!";
//when current month and date is same as birth date and month
else if ( (age.years > 0) && (age.months == 0) && (age.days == 0) )
ageString = age.years + " years old. Happy Birthday!!";
else if ( (age.years > 0) && (age.months > 0) && (age.days == 0) )
ageString = age.years + " years and " + age.months + " months old.";
else if ( (age.years == 0) && (age.months > 0) && (age.days > 0) )
ageString = age.months + " months and " + age.days + " days old.";
else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
ageString = age.years + " years, and" + age.days + " days old.";
else if ( (age.years == 0) && (age.months > 0) && (age.days == 0) )
ageString = age.months + " months old.";
//when current date is same as dob(date of birth)
else ageString = "Welcome to Earth! <br> It's first day on Earth!";
//display the calculated age
return document.getElementById("result").innerHTML = ageString;
}
}
</script>
</head>
<body>
<center>
<h2 style="color: 32A80F" align="center"> Calculate Age from Date of Birth <br> <br> </h2>
<b> Enter Date of Birth: <input type=date id = DOB> </b>
<span id = "message" style="color:red"> </span> <br><br>
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br><br>
<h3 style="color:32A80F" id="result" align="center"></h3>
</center>
</body>
</html>
输出
通过执行上述代码,将会出现一个HTML表单。在这里,从日历中选择一个日期(出生日期),然后点击 计算年龄 按钮来计算所提供的出生日期的年龄。
如果你选择一个日期然后点击计算年龄,会显示一个错误。
我们会根据不同的日期输入值给你展示不同的输出。你会看到响应以 年、月和日 的形式返回。逐个查看输出结果:
输入一个随机日期时的输出结果
输入一个和出生年月日相同的日期的输出结果
输入当前日期时的输出结果:
有多种计算年龄的方法。这是另一种按年、月和天的格式计算年龄的示例。
示例4
在这个示例中,我们通过将日期差异转换为毫秒来计算年龄。这也是一种简单的计算年龄的方法。
<html>
<head>
<script>
function ageCalculator() {
//collect input from HTML form and convert into date format
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
//check user provide input or not
if(userinput==null || userinput==''){
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
}
//execute if user entered a date
else {
//extract and collect only date from date-time string
var mdate = userinput.toString();
var dobYear = parseInt(mdate.substring(0,4), 10);
var dobMonth = parseInt(mdate.substring(5,7), 10);
var dobDate = parseInt(mdate.substring(8,10), 10);
//get the current date from system
var today = new Date();
//date string after broking
var birthday = new Date(dobYear, dobMonth-1, dobDate);
//calculate the difference of dates
var diffInMillisecond = today.valueOf() - birthday.valueOf();
//convert the difference in milliseconds and store in day and year variable
var year_age = Math.floor(diffInMillisecond / 31536000000);
var day_age = Math.floor((diffInMillisecond % 31536000000) / 86400000);
//when birth date and month is same as today's date
if ((today.getMonth() == birthday.getMonth()) && (today.getDate() == birthday.getDate())) {
alert("Happy Birthday!");
}
var month_age = Math.floor(day_age/30);
day_age = day_age % 30;
var tMnt= (month_age + (year_age*12));
var tDays =(tMnt*30) + day_age;
//DOB is greater than today's date, generate an error: Invalid date
if (dob>today) {
document.getElementById("result").innerHTML = ("Invalid date input - Please try again!");
}
else {
document.getElementById("result").innerHTML = year_age + " years " + month_age + " months " + day_age + " days"
}
}
}
</script>
</head>
<body>
<center>
<h2 style="color: #008CBA" align="center"> Calculate Age from Date of Birth <br> <br> </h2>
<b> Enter Date of Birth: <input type=date id = DOB> </b>
<span id = "message" style="color:red"> </span> <br><br>
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br><br>
<h3 style="color:#008CBA" id="result" align="center"></h3>
</center>
</body>
</html>
输出
在下面的输出中,给定出生日期为 15-05-1986 的年龄为 34年5个月17天 。
通过输入一个大于今天的出生日期,会显示一个错误 无效的日期输入 。请参考下面的输出: