一、js实现时间代码
<script type="text/javascript">function showtime(){
var date=new Date()
var year=date.getFullYear()
var month=date.getMonth()+1
var day=date.getDay()
var hours=date.getHours()
var minutes=date.getMinutes()
var seconds=date.getSeconds()
if(day==0){
day=='日'
}
if(seconds<10){
seconds="0"+seconds
}
if (minutes<10) {
minutes="0"+minutes
}
if (hours<10) {
hours="0"+hours
}
var time=year+"/"+month+"/"+day+" "+hours+":"+minutes+":"+seconds
var o=document.getElementById("box")
o.innerHTML=time
setTimeout(showtime,1000)
}
showtime()
</script>
二、注意点
(1)用给变量赋予时间函数,月份要+1;
(2)将时间封装在函数中,好使用setTimeout(showtime,1000)
(3)var o=document.getElementById("box")()中写入想加到的div中的id选择符
(3)o.innerHTML=time是在HTML调用函数重要的语句
(4)该js必须放在想添加的div下面
JS显示动态的日期时间,参考如下:
<body><span id="localtime">2013-10-30 12:33:02 星期三</span>
<script type="text/javascript">
function showLocale(objD)
{
var str,colorhead,colorfoot
var yy = objD.getYear()
if(yy<1900) yy = yy+1900
var MM = objD.getMonth()+1
if(MM<10) MM = '0' + MM
var dd = objD.getDate()
if(dd<10) dd = '0' + dd
var hh = objD.getHours()
if(hh<10) hh = '0' + hh
var mm = objD.getMinutes()
if(mm<10) mm = '0' + mm
var ss = objD.getSeconds()
if(ss<10) ss = '0' + ss
var ww = objD.getDay()
if ( ww==0 ) colorhead="<font color=\"red\">"
if ( ww > 0 && ww < 6 ) colorhead="<font color=\"red\">"
if ( ww==6 ) colorhead="<font color=\"red\">"
if (ww==0) ww="星期日"
if (ww==1) ww="星期一"
if (ww==2) ww="星期二"
if (ww==3) ww="星期三"
if (ww==4) ww="星期四"
if (ww==5) ww="星期五"
if (ww==6) ww="星期六"
colorfoot="</font>"
str = colorhead + yy + "-" + MM + "-" + dd + " " + hh + ":" + mm + ":" + ss + " " + ww + colorfoot
return(str)
}
function tick()
{
var today
today = new Date()
document.getElementById("localtime").innerHTML = showLocale(today)
window.setTimeout("tick()", 1000)
}
tick()
</script>
</body>