根据出生日期换算岁

            getAge(strAge) {
                let birArr = strAge.split("-");
                let birYear = birArr[0];
                let birMonth = birArr[1];
                let birDay = birArr[2];
                d = new Date();
                var nowYear = d.getFullYear();
                var nowMonth = d.getMonth() + 1; //记得加1
                var nowDay = d.getDate();
                var returnAge;
                if (birArr == null) {
                    return false
                };
                var d = new Date(birYear, birMonth - 1, birDay);
                if (d.getFullYear() == birYear && (d.getMonth() + 1) == birMonth && d.getDate() == birDay) {
                    if (nowYear == birYear) {//同年 则为0岁
                        returnAge = 0;
                    } else {
                        var ageDiff = nowYear - birYear; //年之差
                        if (ageDiff > 0) {
                            if (nowMonth == birMonth) {
                                var dayDiff = nowDay - birDay; // //日之差
                                if (dayDiff < 0) {
                                    returnAge = ageDiff - 1;
                                } else {
                                    returnAge = ageDiff;
                                }
                            } else {
                                var monthDiff = nowMonth - birMonth; // //月之差
                                if (monthDiff < 0) {
                                    returnAge = ageDiff - 1;
                                } else {
                                    returnAge = ageDiff;
                                }
                            }
                        } else {
                            return  "出生日期晚于今天,数据有误"; //返回-1 表示出生日期输入错误 晚于今天
                        }
                    }
                    return returnAge;
                    
                } else {
                    return ("输入的日期格式错误!");
                }
            },

 

posted @ 2020-10-21 19:41  曦雨幽兰  阅读(326)  评论(0编辑  收藏  举报