效果如圖:

代碼如下:
<html>
<head>
<title>js獲取當前時間並實時刷新</title>
<script>
//頁面加載調用
window.onload=function(){
//每1秒刷新時間
setInterval("NowTime()",1000);
}
function NowTime(){
var myDate=new Date();
var y = myDate.getFullYear();
var M = myDate.getMonth()+1; //獲取當前月份(0-11,0代表1月)
var d = myDate.getDate(); //獲取當前日(1-31)
var h = myDate.getHours(); //獲取當前小時數(0-23)
var m = myDate.getMinutes(); //獲取當前分鍾數(0-59)
var s = myDate.getSeconds(); //獲取當前秒數(0-59)
//檢查是否小於10
M=check(M);
d=check(d);
h=check(h);
m=check(m);
s=check(s);
var timestr = y+"-"+M+"-"+d+" "+h+":"+m+":"+s;
document.getElementById("nowtime").innerHTML="當前時間:" + timestr;
}
//時間數字小於10,則在之前加個“0”補位。
function check(i){
var num = (i<10)?("0"+i) : i;
return num;
}
</script>
</head>
<body>
<div id="nowtime">在這里顯示時間</div>
</body>
</html>
