找了三个方法 都是转载的,我给优化了下。
方法一:(全浏览器兼容)
<html>
<head>
</head>
<body οnlοad="startTime()">
<div id="ShowTime"></div>
</body>
</html>
<script type="text/javascript">
<!--
function startTime()
{
var today=new Date()
var years=today.getFullYear();
var months=today.getMonth();
var d=today.getDate()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
// add a zero in front of numbers<10
months=months+1
months=checkTime(months)
d=checkTime(d)
m=checkTime(m)
s=checkTime(s)
var weekday=new Array(7)
weekday[0]="星期日"
weekday[1]="星期一"
weekday[2]="星期二"
weekday[3]="星期三"
weekday[4]="星期四"
weekday[5]="星期五"
weekday[6]="星期六"
var w=weekday[today.getDay()]
document.getElementByIdx_x('ShowTime').innerHTML=years+"年"+months+"月"+d+"日 "+w+" "+h+":"+m+":"+s;
t=setTimeout('startTime()',500)
}
function checkTime(i)
{
if (i<10)
{i="0" + i}
return i
}
-->
</script>
方法二:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>用JS实现显示当前时间(实时变化)</title>
<script language="Javascript" type="text/javascript">
setInterval("timer.innerHTML=new Date().toLocaleString()");
</script>
</head>
<body>
<div id="timer">
</div>
</body>
</html>
方法三:
<html>
<body>
//定义一个tick函数,以获取系统的时间
function tick()
{
var year,month,day,hours,minutes,seconds,ap;
var intYear,intMonth,intDay,intHours,intMinutes,intSeconds;
var today;
today=new Date();
intYear=today.getYear();
intMonth=today.getMonth()+1;
intDay=today.getDate();
intHours=today.getHours();
intMinutes=today.getMinutes();
intSeconds=today.getSeconds();
//获取系统时间的小时数
if(intHours==0)
{
hours=intHours+":";
ap="凌晨";
}
else if(intHours<12)
{
hours=intHours+":";
ap="早晨";
}
else if(intHours==12)
{
hours=intHours+":";
ap="中午";
}
else
{
intHours=intHours-12;
hours=intHours+":";
ap="下午";
}
//获取系统时间的分数
if(intMinutes<10)
{
minutes="0"+intMinutes+":";
}
else
{
minutes=intMinutes+":";
}
//获取系统时间的秒数
if(intSeconds<10)
{
seconds="0"+intSeconds+" ";
}
else
{
seconds=intSeconds+" ";
}
timeString=intYear+'年'+intMonth+'月'+intDay+'日'+hours+minutes+seconds+ap;
Clock.innerHTML=timeString;
//每隔0.1秒钟执行一次tick函数
window.setTimeout("tick()",100);
}
window.οnlοad=tick;
</script><div id="Clock"></div>
</body>
</html>