The method is very simple and the code is very concise. Just present the code
The code copy is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js get the current time displayed on the page</title>
<script>
window.onload=function(){
//The timer calls fnDate() once per second
setInterval(function(){
fnDate();
},1000);
}
//js get the current time
function fnDate(){
var oDiv=document.getElementById("div1");
var date=new Date();
var year=date.getFullYear();//Current year
var month=date.getMonth();//Current month
var data=date.getDate();//day
var hours=date.getHours();//hours
var minute=date.getMinutes();//minute
var second=date.getSeconds();//second
var time=year+"-"+fnW((month+1))+"-"+fnW(data)+" "+fnW(hours)+":"+fnW(minute)+":"+fnW(second);
oDiv.innerHTML=time;
}
//Complete when a field is not a two-digit number and fills up 0.
function fnW(str){
var num;
str>10?num=str:num="0"+str;
return num;
}
</script>
</head>
<body>
<div id="div1"> </div>
</body>
</html>