js页面及时显现时候

本日做了一个笔试,让及时显现当前时候,返来今后,本身着手敲代码,然则发明一个题目,经由过程getMonth()获得月份,老是会比当前月份少1,深深地以为实践出真知啊……之前以为Date对象挺简朴的,有许多细节都没有注重。此次认认真真又从新看了相关内容,现把须要注重的处所总结以下:1、经由过程getDay()获得的礼拜数是从0最先,0示意礼拜天,以后从1~6顺次示意礼拜一到礼拜六;
2、获得日期需运用getDate()而不是getDay(),由于能够习气性地以为日期就是天数,能够会运用getDay(),但实在getDay()是用于获得礼拜数的;
3、经由过程getMonth()获得月份,从0最先计数,所以须要再加1。
代码以下:

<html>
<head>
    <title></title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <link rel="stylesheet" type="text/css" href="">
    <script type="text/javascript"></script>
    <style type="text/css">
        input{
            width: 200px;
        }
    </style>
</head>
<body>
    <input id="input">
    <script type="text/javascript">
        var in_1 = document.getElementById('input');
        function showTime(){
            var date = new Date();
            var week = date.getDay();
            var weekday;
            switch(week){
                case 0: weekday = '礼拜天';break;
                case 1: weekday = '礼拜一';break;
                case 2: weekday = '礼拜二';break;
                case 3: weekday = '礼拜三';break;
                case 4: weekday = '礼拜四';break;
                case 5: weekday = '礼拜五';break;
                case 6: weekday = '礼拜六';break;
            }
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hour = date.getHours();
            var minute = date.getMinutes();
            var second = date.getSeconds();
            var in_1 = document.getElementById('input');
            in_1.value = year + '年' + month + "月" + day + '日'+' ' + weekday + ' ' + hour + ':' + minute + ':' + second;
            setTimeout(showTime,1000);
        }
        showTime();
    </script>
</body>
</html>
    原文作者:kvera
    原文地址: https://segmentfault.com/a/1190000007231613
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞