web怎么求年龄。。。。。。。。。。。。。。。。。。。。。。。。
?????
function getAge(strAge) {
d = new Date();
var nowYear = d.getFullYear();
var nowMonth = d.getMonth() + 1; //记得加1
var nowDay = d.getDate();
var returnAge;
var d = new Date(strAge);
var birYear = d.getFullYear();
var birMonth = d.getMonth() + 1;
var birDay = d.getDate();
if (
d.getFullYear() == birYear &&
d.getMonth() + 1 == birMonth &&
d.getDate() == birDay
) {
if (nowYear == birYear) {
returnAge = 0; //
} else {
var ageDiff = nowYear - birYear; //
if (ageDiff > 0) {
if (nowMonth == birMonth) {
var dayDiff = nowDay - birDay; //
if (dayDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
} else {
var monthDiff = nowMonth - birMonth; //
if (monthDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
}
} else {
return "出生日期晚于今天,数据有误"; //返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge;
} else {
return "输入的日期格式错误!";
}
}
console.log(getAge('2012-10-12'));
有用记得给个采纳
public int GetAgeByBirthdate(DateTime birthdate)
{
DateTime now = DateTime.Now;
int age = now.Year - birthdate.Year;
if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day))
{
age--;
}
return age < 0 ? 0 : age;
}
C#更简单,掉这个方法。传日期进来