JavaScript实时显示当前时间

时间:2024-01-27 12:58:31

1、HTML部分

<div id="div1">显示当前时间!</div>

2、css部分

#div1 {
            width: 700px;
            height: 50px;
            border: 1px solid #000;
            margin: 100px auto;
            text-align: center;
            font-size: 20px;
            line-height: 50px;
}

3、JavaScript部分

function showTime(){
    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth() + 1;//0~11
    var date = d.getDate();

    var week = d.getDate();//0~6 0是周末

    week = numOfChinese(week);

    var hour = doubleNum(d.getHours());
    var min = doubleNum(d.getMinutes());
    var sec = doubleNum(d.getSeconds());

    var str = year + "年" + month + "月" + date + "日 星期" + week + " " + hour + ":" + min + ":" + sec;
    return str;
 }

setInterval(function(){
            var timer = document.getElementById("div1");
            timer.innerHTML = showTime();
        },1000);