JavaScript根据出生日期获取年龄

JavaScript根据出生日期获取年龄

参考:

https://stackoverflow.com/questions/10008050/get-age-from-birthdate

 

function genAge(birthday, current) {                        // birthday出生日期,current某一天的日期
    var _birthday = new Date(birthday.replace(/-/g,"/"));
    var _current = new Date(current.replace(/-/g,"/"));

    var birthday_date = _birthday;
    var birth_year = birthday_date.getFullYear();
    var birth_month = birthday_date.getMonth();
    var birth_day = birthday_date.getDate();

    var today_date = _current;
    var today_year = today_date.getFullYear();
    var today_month = today_date.getMonth();
    var today_day = today_date.getDate();
    var age = today_year - birth_year;
    if (today_month < (birth_month - 1)){
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day)){
        age--;
    }
    return age;
}

 

posted on 2020-04-21 16:48  /***/  阅读(375)  评论(0)    收藏  举报

导航