// 获取当前月
function getDate(date) {
let d = new Date(date);
// 将日期设置为下月一号
d.setMonth(d.getMonth() + 1);
d.setDate('1');
// 获取本月最后一天
d.setDate(d.getDate() - 1);
return d.getDate();
}
// 获取年龄 传出生日期和当前日期,当前日期可以不用传
function getAge(birthday = '', lastDay = "") {
// 没有传生日不计算
if (!birthday) return
// 先截取到字符串中的年、月、日
let selectYear = birthday.split('-')[0]
let selectMonth = birthday.split('-')[1]
let selectDay = birthday.split('-')[2]
// 得到当前时间的年、月、日
let cal = lastDay === '' ? new Date() : new Date(lastDay);
let yearNow = cal.getFullYear();
let monthNow = cal.getMonth() + 1;
let dayNow = cal.getDate();
// 用当前年月日减去生日年月日
let yearMinus = yearNow - selectYear;
let monthMinus = monthNow - selectMonth;
let dayMinus = dayNow - selectDay;
let age = '';
if (yearMinus < 0) {
return "生日不可小于当前时间"
} else {
if (yearMinus === 0) {
if (monthMinus < 0) {
return '生日不可小于当前时间'
} else {
if (monthMinus > 0) {
if (dayMinus >= 0) {
return monthMinus + '个月' + (dayMinus > 0 ? dayMinus + '天' : '')
}
return ((monthMinus - 1) === 0 ? '' : (monthMinus - 1) + '个月') + (dayNow + (getDate(birthday) - selectDay)) + '天'
} else {
if (dayMinus < 0) {
return '生日不可小于当前时间'
}
return dayMinus + '天'
}
}
} else {
age = yearMinus + '岁'
if (monthMinus === 0) {
if (dayMinus >= 0) {
return age + (dayMinus === 0 ? '' : dayMinus + '天')
}
return (yearMinus - 1 === 0 ? '' : yearMinus - 1 + '岁') + '11个月'
} else if (monthMinus > 0) {
age += (dayMinus >= 0 ? monthMinus + '个月' : (monthMinus - 1 > 0 ? monthMinus + '个月' : (getDate(birthday) - selectDay + dayNow + '天')))
return age;
} else {
return (yearMinus - 1 === 0 ? '' : yearMinus - 1 + '岁') + (12 - selectMonth + monthNow) + '个月'
}
}
}
}
console.log(getAge('2001-07-04'))