Home > Web Front-end > JS Tutorial > body text

JS realizes real-time display of time

不言
Release: 2018-04-03 15:02:56
Original
3259 people have browsed it

This article shares with you about the real-time display of time in JS. Friends who are interested can take a look. Friends who need help can also refer to the previous projects of

There is a need to display the current time in real time on the web page, and the effect is as shown in the figure:


1. html Structure

<p class="col-xs-12 col-sm-6">

      <i class="fa fa-plus-square-o" aria-hidden="true"></i>

      <span id="current-time"></span>
</p>
Copy after login


2. JS

/*实时显示时间*/

 function showtime(){

    var today,hour,second,minute,year,month,date;

    var strDate ;

    today=new Date();

    var n_day = today.getDay();

    switch (n_day){

        case 0:{

          strDate = "星期日"

        }break;

        case 1:{

          strDate = "星期一"

        }break;

        case 2:{

          strDate ="星期二"

        }break;

        case 3:{

          strDate = "星期三"

        }break;

        case 4:{

          strDate = "星期四"

        }break;

        case 5:{

          strDate = "星期五"

        }break;

        case 6:{

          strDate = "星期六"

        }break;

        case 7:{

          strDate = "星期日"

        }break;

    }

    year = today.getFullYear();

    month = today.getMonth()+1;

    date = today.getDate();

    hour = today.getHours();

    minute =today.getMinutes();

    second = today.getSeconds();

 

    if (month >= 1 && month <= 9) {

        month = "0" + month;

    }

    if (date >= 0 && date <= 9) {

        date = "0" + date;

    }

    if (hour >= 0 && hour <= 9) {

        hour = "0" + hour;

    }

    if (minute >= 0 && minute <= 9) {

        minute = "0" + minute;

    }

    if (second >= 0 && second <= 9) {

        second = "0" + second;

    }

    document.getElementById(&#39;current-time&#39;).innerHTML ="当前时间:"+ year + "年" + month + "月" + date + "日" +"  "+ strDate +"   " + hour + ":" + minute + ":" + second; //显示时间

    setTimeout("showtime();", 1000); //设定函数自动执行时间为 1000 ms(1 s)

}
Copy after login

Related recommendations:

js to implement login and Registration interface

JS implements AJAX partial refresh (with code)

The above is the detailed content of JS realizes real-time display of time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!