javascript计算年龄

407 阅读1分钟

年龄计算

`function getAge(birthDayDate, targetDate) { birthDayDate = new Date(birthDayDate.replace(/[-.]/g, "/")); targetDate = new Date(targetDate.replace(/[-.]/g, "/")); var birthYear = birthDayDate.getFullYear(); var birthMonth = birthDayDate.getMonth() + 1; var birthDay = birthDayDate.getDate();

        var targetYear = targetDate.getFullYear();
        var targetMonth = targetDate.getMonth() + 1;
        var targetDay = targetDate.getDate();

        var age = targetYear - birthYear;
        if(targetMonth < birthMonth) {
            age -= 1;
        } else if(targetMonth == birthMonth) {
            //是否闰年
            if(birthYear % 4 == 0) {
                if(targetYear % 4 == 0) {
                    if(targetDay < birthDay) {
                        age -= 1;
                    }
                } else if(birthMonth == 2) {
                    if(birthDay == 29) {//判断是不是2.29出生
                        if(targetDay < 28) {
                            age -= 1;
                        }
                    }
                }
            } else {
                if(targetDay < birthDay) {
                    age -= 1;
                }
            }
        }
        return age;
    }`