js通过出生日期计算年龄 - yuzhouxiaogegit/blog GitHub Wiki

function getAge(birthday = '1999-01-01') {
    if (typeof birthday == 'string') {
        birthday = birthday.replace(/\s.*/g, '');
        let result = ((new Date() - new Date(birthday)) / (24 * 60 * 60 * 1000 * 365) + '').split('.');
        if (Number(result[0]) >= 1) {
            return Number(result[0]);
        }
        return Number(result[1] && result[1][0] !== '0' ? result[0] + '.' + result[1][0] : result[0]);
    }
    throw "getAge 方法需要传入日期字符串、列如:1999-01-01";
}

console.log(getAge('2001-01-01'))