实时显示时间(HTML+JS)

方法一:


<p id="time1" style="color: blueviolet;">p>
<script>
    function mytime(){
        var a = new Date();
        var b = a.toLocaleTimeString();
        var c = a.toLocaleDateString();
        document.getElementById("time1").innerHTML = c+" "+b;
        }
    setInterval(function() {mytime()},1000);
script>

方法二:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript">
function getTime() {

    var dateObj = new Date();

    var year = dateObj.getFullYear();//年
    var month = dateObj.getMonth()+1;//月  (注意:月份+1)
    var date = dateObj.getDate();//日
    var day = dateObj.getDay();
    var weeks = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
    var week = weeks[day];//根据day值,获取星期数组中的星期数。
    var hours = dateObj.getHours();//小时
    var minutes = dateObj.getMinutes();//分钟
    var seconds = dateObj.getSeconds();//秒

    if(month<10){
        month = "0"+month;
    }
    if(date<10){
        date = "0"+date;
    }
    if(hours<10){
        hours = "0"+hours;
    }
    if(minutes<10){
        minutes = "0"+minutes;
    }
    if(seconds<10){
        seconds = "0"+seconds;
    }

    var newDate = year+"年"+month+"月"+date+"日"+hours+":"+minutes+":"+seconds+"   "+week;
    document.getElementById("date1").innerHTML = "时间显示:" + newDate;//在div中写入时间
    setTimeout('getTime()', 500);//每隔500ms执行一次getTime()
}
script>

<title>实时显示时间title>
head>
<body onload="getTime()">
    <div id="date1">div>
body>
html>

区别:
*setInterval在执行完一次代码之后,经过了那个固定的时间间隔,它还会自动重复执行代码。
而setTimeout只执行一次那段代码。*

你可能感兴趣的:(前端web)