10.JavaScript距离生日还有多少天、根据出生年月日计算年龄

1.距离生日还有多少天:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //给出生日的月份和日期,计算还有多少天过生日
        function getDaysToBirthday(month, day) {
            var nowTime = new Date();
            var thisYear = nowTime.getFullYear();
            //今年的生日
            var birthday = new Date(thisYear, month - 1, day);

            //今年生日已过,则计算距离明年生日的天数
            if (birthday < nowTime) {
                birthday.setFullYear(nowTime.getFullYear() + 1);
            }
            var timeDec = birthday - nowTime;
            var days = timeDec / (24 * 60 * 60 * 1000);
            return Math.ceil(days);
        }
        getDaysToBirthday(11, 2);
    </script>
</body>

</html>
index.html

2.根据出生年月日,计算年龄:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //是否闰年
        function isLeap(year){
            return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
        }

        //根据出生年月日,计算年龄
        function getAge(year, month, day) {
            //得到当前日期
            var nowTime = new Date();
            
            var age = nowTime.getFullYear() - year;//粗略计算出年龄

            //若生日是2月29日,且今年不是闰年,则今年生日日期按28日计算
            if(month === 2 && day === 29 && !isLeap(nowTime.getFullYear())){
                day = 28;
            }

            //得到今年的生日日期
            var nowBirthday = new Date(nowTime.getFullYear(), month - 1, day);
            console.log(nowBirthday, nowTime);
            if(nowBirthday > nowTime){//若今年的生日没有过,则减一岁
                age--;
            }

            return age;
        }

        console.log(getAge(2000, 2, 29));
    </script>
</body>

</html>
index.html

猜你喜欢

转载自www.cnblogs.com/lanshanxiao/p/12758708.html