自己封装函数,根据需求拼接时间格式更新实时时间
<body>
<div id="demo"></div>
</body>
<script>
//判断是否小于10,小于10补0
function createZero(n){
if(n<10){
return "0"+n;
}
return n;
}
//封装函数,获取各种时间,方便自己组装格式
function time(){
var d=new Date;
var year=createZero(d.getFullYear());
var month=createZero(d.getMonth()+1)
var date=createZero(d.getDate())
var day=d.getDay()
var hours=createZero(d.getHours())
var mimu=createZero(d.getMinutes())
var sec=createZero(d.getSeconds())
var mill=d.getMilliseconds()
switch(day){
case 0:day="日";break;
case 1:day="一";break;
case 2:day="二";break;
case 3:day="三";break;
case 4:day="四";break;
case 5:day="五";break;
case 6:day="六";break;
}
return obj= {
year:year,
month:month,
date:date,
day:day,
hours:hours,
mimu:mimu,
sec:sec,
mill:mill
};
}
//自己拼接格式
function ti(){
time()
var t= obj.year+"-"+obj.month+"-"+obj.date + " "+obj.hours+":"+obj.mimu+":"+obj.sec;
return t;
}
//进行计时器输出
var myTimer=setInterval(function(){
document.getElementById("demo").innerHTML= ti()
},1000);
</script>
也可以直接获取拼接输出
<script>
var myVar=setInterval(function(){
myTimer()
},1000);
function myTimer(){
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
</script>