1.根据日期算年龄
mymethod(birthday){
if(birthday){
birthday=birthday.split('-');
let date = new Date();
let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
let age = today.map((val, index) => {
return val - birthday[index]
})
if (age[2] < 0) {
let lastMonth = new Date(today[0], today[1], 0)
age[1]--
age[2] += lastMonth.getDate()
}
if (age[1] < 0) {
age[0]--
age[1] += 12
}
console.log(age[0]+'岁'+age[1]+'月'+age[2]+'天');
}
}
2.根据年龄算日期
myfunction(ageYear,ageMonth,ageDay){
var subYear = parseInt(ageYear);
var subMonth = parseInt(ageMonth);
var subDay = parseInt(ageDay);
var now = new Date();
var nowYear = now.getFullYear();
var nowMonth = now.getMonth()+1;
var nowDay = now.getDate();
var day = nowDay - subDay;
var month = nowMonth - subMonth;
var year = nowYear - subYear;
if(day<=0){
var lastMonth = nowMonth - 1;
var lastMonthOfYear = nowYear;
if(lastMonth<=0){
lastMonth =lastMonth + 12
lastMonthOfYear = lastMonthOfYear - 1;
}
day = day + new Date(lastMonthOfYear, lastMonth, 0).getDate();
month = month - 1;
}
if(month<=0){
month =month + 12
year--;
}
if(month<10){
month='0'+month
}
if(day<10){
day='0'+day
}
console.log(year+'-'+month+'-'+day);
}