例如出生 10个月 2岁
getDate(date) {
let d = new Date(date);
return new Date(d.getFullYear(), d.getMonth()+1, 0).getDate();
},
getAge(birthday, lastDay=this.$moment(new Date()).format('YYYY-MM-DD')) {
//this.$moment(new Date()).format('YYYY-MM-DD')) 这段作用就是默认获取当前日期时间转换为YYYY-MM-DD的格式,这个方法有很多 就没写了
// console.log(birthday,lastDay);
// 先截取到字符串中的年、月、日
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 + '个月'
}
if((monthMinus - 1) === 0){
return (dayNow + (this.getDate(birthday) - selectDay)) + '天'
}else{
return (monthMinus - 1) + '个月'
}
} else {
if (dayMinus < 0) {
return '生日不可小于当前时间'
}
return dayMinus + '天'
}
}
} else {
age = yearMinus + '岁'
if (monthMinus === 0) {
if (dayMinus >= 0) {
return age
}
if(yearMinus - 1 === 0){
return '11个月'
}else{
return yearMinus - 1 + '岁'
}
} else if (monthMinus > 0) {
return age;
} else {
if(yearMinus - 1 === 0){
return (12 - selectMonth + monthNow) + '个月'
}else{
return yearMinus - 1 + '岁'
}
}
}
}
},