首页 > 代码库 > JS练习-简单显示时间

JS练习-简单显示时间

<html>
    <head>
        <title>简单时间显示</title>
        <style>
            div{
                height:60px;
                background-color:lightgray;
            }
        </style>
        <script>
            function showTime(){
                var time=new Date();//创建时间对象,获得当前时间
                
                var hour,minute,second;//提取时分秒
                hour=time.getHours();
                minute=time.getMinutes();
                second=time.getSeconds();
                
                //分、秒小于10的时候,应该显示为0*
                minute=checkTime(minute);
                second=checkTime(second);
                
                var year,month,day;//提取年月日,月从0开始,所以加1
                year=time.getFullYear();//getYear()函数获得的是现在的年份-1900
                month=time.getMonth()+1;
                day=time.getDate();
                
                var weekday;
                weekday=time.getDay();//星期weekday:weekday=0~6:星期日~星期六
                var weekDays=new Array("日","一","二","三","四","五","六");
                
                //写入到html
                var x=document.getElementById("p-time");
                var str=year+"年"+month+"月"+day+"日"+" "+"星期"+weekDays[day]+" "+hour+":"+minute+":"+second;
                x.innerHTML=str;
                
                setTimeout(‘showTime()‘,500);//每500毫秒调用一次showTime函数来刷新。一定注意函数的大小写
            }
            function checkTime(x){
            //这里不能写成var x:
                if(x<10){
                    x=‘0‘+x;
                }
                return x;
            }
        </script>
    </head>
    <body onl oad="showTime()">
        <div>
            <p id="p-time"></p>
        </div>
    </body>
</html>

效果图:

技术分享

 

JS练习-简单显示时间