HTML:在浏览器页面上简单实现显示标准系统时间
运用到了HTML JavaScript中的Date对象,并按 “日期 时间 星期” 格式输出,且要求为除年份外皆为两位(不足两位前补0),最后的全代码如下
<!DOCTYPE html>
<html>
<head>
<script>
function time(){
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
var week = date.getDay();
week="星期"+"日一二三四五六".charAt(week);
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
var temp=[month,day,hour,minute,second];
for (var i in temp) {
temp[i]=temp[i]<10?"0"+temp[i]:temp[i];
}
var currentTime = year +"-"+ temp[0] +"-"+ temp[1] +" "+ temp[2] +":"+ temp[3] +":"+ temp[4] +" "+week;
document.getElementById("time").innerHTML = currentTime;
}
setInterval("time()",1000);
</script>
</head>
<body onload="time()">
<span id="time"></span>
</body>
</html>
优化:1.其中补足两位代码本来用每行变量下加三目运算符实现
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
month = month<10?"0"+month:month;
var day = date.getDate();
day = day<10?"0"+day:day;
var week = date.getDay();
var weeks="星期"+"日一二三四五六".charAt(week);
var hour = date.getHours();
hour = hour<10?"0"+hour:hour;
var minute = date.getMinutes();
minute = minute<10?"0"+minute:minute;
var second = date.getSeconds();
second = second<10?"0"+second:second;
document.getElementById("time").innerHTML=year+"-"+month+"-"+day+"-"+hour+"-"+minute+"-"+second+"-"+week;
后为减少代码量,结合以前所学改用数组改进了一下
var temp=[month,day,hour,minute,second];
for (var i in temp) {
temp[i]=temp[i]<10?"0"+temp[i]:temp[i];
}
var currentTime = year +"-"+ temp[0] +"-"+ temp[1] +" "+ temp[2] +":"+ temp[3] +":"+ temp[4] +" "+week;
2. 关于星期 getDay()的默认值为0~6,显示要成中文的数字,不能简单的加1,本是用switch结构使0~6对应到日~六,这样的代码量也较多,后使用了charAt(),恰好week变量的值为常数,较简单的地实现了显示星期
var week="星期"+"日一二三四五六".charAt(week);