根据年月日计算年龄(周岁)
2019-05-16 本文已影响0人
奔跑的小孩_79d2
// JS日期系列:根据出生日期 得到周岁年龄
export function getAge (strBirthday) {
let returnAge
const strBirthdayArr = strBirthday.split('-')
const birthYear = strBirthdayArr[0] * 1
const birthMonth = strBirthdayArr[1] * 1
const birthDay = strBirthdayArr[2] * 1
const d = new Date()
const nowYear = d.getFullYear()
const nowMonth = d.getMonth() + 1
const nowDay = d.getDate()
if (nowYear === birthYear) {
returnAge = 0 // 同年 则为0岁
} else {
const ageDiff = nowYear - birthYear // 年之差
if (ageDiff > 0) {
if (nowMonth === birthMonth) {
const dayDiff = nowDay - birthDay // 日之差
if (dayDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
} else {
const monthDiff = nowMonth - birthMonth // 月之差
if (monthDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
}
} else {
returnAge = -1 // 返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge // 返回周岁年龄
}