方法很簡(jiǎn)單,代碼也很簡(jiǎn)潔,直接奉上代碼吧
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js獲取當(dāng)前時(shí)間顯示在頁(yè)面上</title>
<script>
window.onload=function(){
//定時(shí)器每秒調(diào)用一次fnDate()
setInterval(function(){
fnDate();
},1000);
}
//js 獲取當(dāng)前時(shí)間
function fnDate(){
var oDiv=document.getElementById("div1");
var date=new Date();
var year=date.getFullYear();//當(dāng)前年份
var month=date.getMonth();//當(dāng)前月份
var data=date.getDate();//天
var hours=date.getHours();//小時(shí)
var minute=date.getMinutes();//分
var second=date.getSeconds();//秒
var time=year+"-"+fnW((month+1))+"-"+fnW(data)+" "+fnW(hours)+":"+fnW(minute)+":"+fnW(second);
oDiv.innerHTML=time;
}
//補(bǔ)位 當(dāng)某個(gè)字段不是兩位數(shù)時(shí)補(bǔ)0
function fnW(str){
var num;
str>10?num=str:num="0"+str;
return num;
}
</script>
</head>
<body>
<div id="div1"> </div>
</body>
</html>
更多信息請(qǐng)查看IT技術(shù)專欄