友情提示:ios日期格式只支援 2020/04/15
話不多說,上程式碼(#.#)
// 根據日期計算年齡
getAge(strBirthday) {
//strBirthday傳入格式 2020-04-15
var returnAge;
var strBirthdayArr = strBirthday.split('-');
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) {
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; //返回週歲年齡
},