备注:
本例子中有两个参数 一个是出生日期另外一个是当前日期格式都是"1995-06-24"这种格式,能够精确算出岁月*天,具体实现代码如下
javascript
/**
*
* @param birthDay 出生日期
* @param curDate 当前日期
* @returns
*/
export const birthToAgeDiff = (birthDay: string, curDate: string) => {
const birth = dayjs(birthDay);
const now = dayjs(curDate);
if(birth.valueOf()> now.valueOf()) return '未出生~'
let years = now.year() - birth.year();
let months = now.month() - birth.month();
let days = now.date() - birth.date();
if (days < 0) {
months -= 1;
days += dayjs(now).subtract(1, 'month').daysInMonth();
}
if (months < 0) {
years -= 1;
months += 12;
}
return ` ${years}岁${months}月${days}天`
};