年龄计算得出周岁,不精确算出月日,即只显示几岁
/**
* 根据生日得到年龄
* @param {String | Date | Number} [birthday] 生日
* @returns {Number}
*/
function getAgeByBirth(birthday){
let age;
const nowDate = new Date();
const birthDate = birthday ? new Date(birthday) : new Date();
const nowY = nowDate.getFullYear();
const birthY = birthDate.getFullYear();
const nowM = nowDate.getMonth();
const birthM = birthDate.getMonth();
const nowD = nowDate.getDate();
const birthD = birthDate.getDate();
if (nowDate.getTime() < birthDate.getTime()) {
age = 0;
} else {
if (nowY == birthY) {
age = 0;
} else {
age = nowY - birthY;
if (nowM < birthM) {
age--;
} else if (nowM == birthM && nowD < birthD) {
age--;
}
}
}
return age;
}
计算岁数精确到天
最近遇到需求要计算出不足两岁的得出一岁几月,不足一岁的得出几月几天,不足月的得出几天。由于计算天数涉及到获取前一月份天数,月份天数涉及到是否闰年的2月,以及跨年等情况。计算逻辑复杂,因此借助moment库进行处理。
import moment from 'moment';
/**
* 根据生日得到年龄
* @param {Moment|String|Number|Date|Array} [birth] 生日
* @returns {String}
*/
function getAgeByBirth(brith) {
if (!brith) return '';
const duration = moment.duration(moment().diff(brith));
const years = duration.years();
const months= duration.months();
const days= duration.days();
let result = '';
if (years > 1) {
result = years + '岁';
} else {
if (years === 1) {
result = years + '岁' + months + '月';
} else if (months > 0) {
result = months + '月' + days + '天';
} else {
result = days + '天';
}
}
return result;
}