下边是我在工作中遇到的一个关于计算一个人周岁的问题分为2种情况
第一种情况是生日当天加1岁
第二种情况是生日过后那天加1岁
本人为刚入行的小朋友,如果觉得有问题或者更见的问题患有留言并提意见
1.第一种情况是生日当天加1岁
//strBirthday为YYYY-MM-DD的格式
function jsGetAge(strBirthday) {
var returnAge;
var strBirthdayArr;
if (_.isString(strBirthday)) {
strBirthdayArr = strBirthday.split("-");
} else if (_.isDate(strBirthday)) {
strBirthdayArr = [
strBirthday.getFullYear(),
strBirthday.getMonth() + 1,
strBirthday.getDate()
];
}
var birthYear = strBirthdayArr[0];
var birthMonth = strBirthdayArr[1];
var birthDay = strBirthdayArr[2];
var d = new Date();
var nowYear = d.getFullYear();
var nowMonth = d.getMonth() + 1;
var nowDay = d.getDate();
if (nowYear == birthYear) {
returnAge = 0;//同年 则为0岁
} else {
var ageDiff = nowYear - birthYear; //年之差
if (ageDiff > 0) {
console.log(birthYear,birthMonth,birthDay,'现在',nowYear,nowMonth,nowDay,'年之差',ageDiff)
if (nowMonth == birthMonth) {
var dayDiff = nowDay - birthDay;//日之差
console.log(dayDiff);
// if (dayDiff <= 0) {
if (dayDiff < 0) {
returnAge = ageDiff - 1;
} else if(dayDiff > 0){
returnAge = ageDiff+1;
} else if(dayDiff == 0){
returnAge = ageDiff;
}
} else {
var monthDiff = nowMonth - birthMonth;//月之差
if (monthDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
}
} else {
returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge;//返回周岁年龄
},
2.第二种情况是生日过后那天加1岁
function jsGetAge(strBirthday) {
var returnAge;
var strBirthdayArr;
if (_.isString(strBirthday)) {
strBirthdayArr = strBirthday.split("-");
} else if (_.isDate(strBirthday)) {
strBirthdayArr = [
strBirthday.getFullYear(),
strBirthday.getMonth() + 1,
strBirthday.getDate()
];
}
var birthYear = strBirthdayArr[0];
var birthMonth = strBirthdayArr[1];
var birthDay = strBirthdayArr[2];
var d = new Date();
var nowYear = d.getFullYear();
var nowMonth = d.getMonth() + 1;
var nowDay = d.getDate();
if (nowYear == birthYear) {
returnAge = 0;//同年 则为0岁
} else {
var ageDiff = nowYear - birthYear; //年之差
if (ageDiff > 0) {
if (nowMonth == birthMonth) {
var dayDiff = nowDay - birthDay;//日之差
// if (dayDiff <= 0) {
if (dayDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
} else {
var monthDiff = nowMonth - birthMonth;//月之差
if (monthDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
}
} else {
returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge;//返回周岁年龄
},