1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>计时器</title> 5 <script type="text/javascript"> 6 onload = function () { 7 8 var timeNow = function () { 9 var myDate = new Date(); 10 var year = myDate.getFullYear(); 11 var month = myDate.getMonth() + 1; 12 var day = myDate.getDate(); 13 var hour = myDate.getHours(); 14 var minute = myDate.getMinutes(); 15 var second = myDate.getSeconds(); 16 var p = document.getElementById("p"); 17 p.innerHTML = year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"; 18 19 }
//常规方法: 20 setInterval(timeNow, 1000);
//百度知道的大牛写的简洁方法: 21 setInterval("document.getElementById('p2').innerHTML=new Date().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay());", 1000);
//toLocalString()方法会直接生成“年月日时分秒”格式的时间。
//getDay()方法会返回星期几,0~6分别是周日到周六。
//alert(new Date().toLocaleString());
//alert(new Date().getDay());
22 23 } 24 </script> 25 </head> 26 <body> 27 <p id="p"> 28 </p> 29 <p id="p2"> 30 </p> 31 </body> 32 </html>