根据生日算年龄、根据年龄算生日

        小颖昨天接了个新需求,根据用户生日算年龄,将用户年龄和退休年龄进行对比,判断用户能否办理退休相关业务,然后就有了今日份的文章

话不多说直接上代码··························

根据生日算年龄

        <!--        根据出生日期算年龄-->
        function getAge(birthday) {
            //包含"-"  例如:1994-11-20
            if (birthday.indexOf('-') != -1) {
                birthday = birthday.split('-');
            } else {//不包含"-"  例如:19941120
                birthday = [birthday.slice(0, 4), birthday.slice(4, 6), birthday.slice(6)];
            }
            // 新建日期对象
            let date = new Date();
            // 今天日期,数组,同 birthday
            let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
            // 分别计算年月日差值
            let age = today.map((val, index) => {
                return val - birthday[index]
            })
            // 当天数为负数时,月减 1,天数加上月总天数
            if (age[2] < 0) {
                // 简单获取上个月总天数的方法,不会错
                let lastMonth = new Date(today[0], today[1], 0)
                age[1]--
                age[2] += lastMonth.getDate()
            }
            // 当月数为负数时,年减 1,月数加上 12
            if (age[1] < 0) {
                age[0]--
                age[1] += 12
            }
            console.log(age[0] + '岁' + age[1] + '月' + age[2] + '天');
            return age[0]
        }

        getAge("1994-11-20")
        console.log('------------------------------------------');
        getAge("19941120")

打印结果:

根据年龄算生日

        //根据年龄算出生日期
        function getBirthday(ageYear, ageMonth, ageDay) {
            let subYear = parseInt(ageYear), subMonth = parseInt(ageMonth), subDay = parseInt(ageDay), now = new Date(),
                nowYear = now.getFullYear(), nowMonth = now.getMonth() + 1, nowDay = now.getDate(); // 按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。
            let day = nowDay - subDay, month = nowMonth - subMonth, year = nowYear - subYear; // 检查是否溢出
            if (day <= 0) { // 获得上月的天数
                let lastMonth = nowMonth - 1;
                let lastMonthOfYear = nowYear;
                if (lastMonth <= 0) {
                    lastMonth = lastMonth + 12 //(lastMonth + 12) % 12;
                    lastMonthOfYear = lastMonthOfYear - 1;
                }
                day = day + new Date(lastMonthOfYear, lastMonth, 0).getDate();
                month = month - 1;
            }
            if (month <= 0) {
                month = month + 12 //(month + 12) % 12;
                year--;
            }
            if (month < 10) {
                month = '0' + month
            }
            if (day < 10) {
                day = '0' + day
            }
            console.log(year + '-' + month + '-' + day);
        }

        getBirthday(27, 8, 9)

打印结果:

五点啦,好开心又是美好的周五,今天上完明天放假~~~~~~~~~~~~~~~~~~~不过最近因为疫情,好几个周末都没出门玩耍了,等疫情好点了先请假回趟西安,想念我婆做的户县软面、菜盒、浆水搅团、凉鱼····················好想回家~~~~~~~~~~

晒张我家狗子的美图哈哈

 最后那就祝大家周末愉快拉~~~~~~~~~~~~~~~~~~~~~~~~~

 

posted @ 2022-07-29 17:03  爱喝酸奶的吃货  阅读(141)  评论(2编辑  收藏  举报