将当前系统日期显示为“二零一二年五月六日十七时十九分三十秒”的格式,利用window对象的setInterval方法,还有就是获取日期的年月日时分秒并进行格式转换
<!DOCTYPE html public "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" >
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
function convert(x){ //也可以用数组存储表示
switch(x){
case 0: return "零";
case 1:return "一";
case 2:return "二";
case 3:return "三";
case 4:return "四";
case 5:return "五";
case 6:return "六";
case 7:return "七";
case 8:return "八";
case 9:return "九";
default:break
}
}
function getDate(){
var date=new Date();
var year=date.getFullYear(); //年
var syear=convert(Math.floor(year/1000))+convert(Math.floor((year%1000)/100))+convert(Math.floor(((year%1000)%100)/10))+convert(Math.floor(((year%1000)%100)%10))+"年";
var month=date.getMonth()+1; //月
if(month<9){
var smonth=convert(Math.floor(month%10))+"月";
} else if(Math.floor(month%10)==0){
var smonth="十月";
} else{
smonth=convert(Math.floor(month/10))+convert(Math.floor(month%10))+"月";
}
var da=date.getDate(); //日
if(da<9){
var sda=convert(Math.floor(da%10))+"日";
} else if(Math.floor(da%10)==0){
if(da==10){
var sda="十日";
} else{
var sda=convert(Math.floor(da/10))+"十日";
}
} else{
var sda=convert(Math.floor(da/10))+"十"+ convert(Math.floor(da%10))+"日";
}
var hour=date.getHours(); //时间
if(hour<9){
var sh=convert(Math.floor(hour%10))+"点";
} else if(Math.floor(hour%10)==0){
if(hour==10){
var sh="十点";
} else{
var sh=convert(Math.floor(hour/10))+"十点";
}
} else{
var sh=convert(Math.floor(hour/10))+"十"+convert(Math.floor(hour%10))+"点";
}
var minutes=date.getMinutes(); //分钟
if(minutes<9){
var sm=convert(Math.floor(minutes%10))+"分";
} else if(Math.floor(minutes%10)==0){
if(minutes==10){
var sm="十分";
} else{
var sm=convert(Math.floor(minutes/10))+"十分";
}
} else{
var sm=convert(Math.floor(minutes/10))+"十"+convert(Math.floor(minutes%10))+"分";
}
var second=date.getSeconds(); //秒
if(second<9){
var ss=convert(Math.floor(second%10))+"秒";
} else if(Math.floor(second%10)==0){
if(second==10){
var ss="十秒";
} else{
var ss=convert(Math.floor(second/10))+"十秒";
}
} else{
var ss=convert(Math.floor(second/10))+"十"+convert(Math.floor(second%10))+"秒";
}
var str=syear+smonth+sda+sh+sm+ss;
var div=document.getElementById("box"); //在网页中显示
if(typeof div.textContent=="string"){
div.textContent=str;
} else{
div.innerText=str;
}
}
window.setInterval(getDate,1000); //每隔一秒显示时间
</script>
</body>
</html>
代码仅实现功能,还有许多需要优化的地方