JavaScript,函数的封装练习题,判断日期是否合法

日期是否合法,就需要了解到闰年与平年的二月份天数是不一样的,还有大月份与小月份的天数也是不一样的,用简单的判断语句还是能实现的,但是现在要求给判断日期是否合法封装一个函数,参数分别是年,月,日。这时候就有点困难了,代码如下,我没有用js文件分开封装的函数,比较好观察。

HTML: fiefldset 表单字段集,加个好看的界面,效果如下

<fieldset>
        <legend>日期是否合法</legend>
        <span>年:</span><input type="text" id="inp1">
        <span>月:</span><input type="text" id="inp2">
        <span>日:</span><input type="text" id="inp3">
        <button id="btn">判断</button>
    </fieldset>
复制代码

image.png

 <script>
        //给document.getElementById()函数封装一个简化的函数get
        function get(id) {
            return document.getElementById(id);
        }
        //给判断闰年一个封装,参数n为年份
        function o_year(n) {
            if (n % 4 == 0 && n % 100 != 0 || n % 400 == 0) {
                return true;
            } else return false;
        }
        //给判断日期一个封装,参数year为年份,month为月份,day为天数
        function o_date(year, month, day) {
            //判断年份不能为空,还有不能为小数
            if (year != "" && year % 1 == 0) {
                //判断月份是否合法,不合法直接返回false
                if (month <= 12 && month >= 1 && month % 1 == 0) {
                    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                        //判断大月份是不是31天,不是直接返回false
                        if (day <= 31 && day >= 1 && day % 1 == 0) {
                            return true;

                        } else return false;
                    }
                    if (month == 4 || month == 6 || month == 9 || month == 11) {
                        //判断小月份是不是30天,不是直接返回false
                        if (day <= 30 && day >= 1 && day % 1 == 0) {
                            return true;

                        } else return false;
                    }
                    if (month == 2) {
                        //调用判断闰年的函数,判断参数year是不是闰年
                        if (o_year(year) == true) {
                            //判断二月份是不是29天,不是返回false
                            if (day >= 1 && day <= 29 && day % 1 == 0) {
                                return true;
                            } else return false
                        } else {
                            //判断二月份是不是28天,不是返回false
                            if (day >= 1 && day <= 28 && day % 1 == 0) {
                                return true
                            } else return false
                        }
                    }
                    return true;
                } else return false;
            } else return false
        }

        var oInp1 = get('inp1')
        var oInp2 = get('inp2')
        var oInp3 = get('inp3')
        var oBtn = get('btn')
        oBtn.onclick = function() {
            if (o_date(inp1.value, inp2.value, inp3.value) == true) {
                alert("日期合法")
            } else alert("日期不合法")
        }
    </script>
复制代码

结果如下:闰年二月份天数大于29天,所以日期不合法。

image.png

猜你喜欢

转载自juejin.im/post/7040278362677313573