<script>
// 创建补零函数
function creatZero(n){
if(n<10){
return "0"+n;
}
return n;
}
// 创建格式化日期函数
function getDate(){
var obj = new Date();
var year = obj.getFullYear();
var month = obj.getMonth()+1;
var date = obj.getDate();
var day = obj.getDay();
var hour= obj.getHours();
var minute = obj.getMinutes();
var second = obj.getSeconds();
var mSecond = obj.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 {
year:year,
month:creatZero(month),
date:creatZero(date),
day:day,
hour:creatZero(hour),
minute:creatZero(minute),
second:creatZero(second),
mSecond:mSecond
}
}
// 获取页面的盒子
var timeBox = document.getElementById("box");
// 计时器初始会等待一秒之后执行,所以刷新页面会有一秒空白,计时器前先执行一次可解决
// 然后将代码交给计时器执行即可
var d = getDate();
timeBox.innerHTML = d.year +"年"+ d.month +"月"+ d.date +"日星期"+ d.day +
" "+ d.hour +":" + d.minute +":"+ d.second;
// 利用计时器,每隔一秒,获取并拼接一次
setInterval(function(){
var d = getDate();
box.innerHTML = d.year +"年"+ d.month +"月"+ d.date +"日星期"+ d.day +
" "+ d.hour +":" + d.minute +":"+ d.second;
}, 1000);
</script>