这次给大家分享的是让js实时显示当前时间信息,包括:年月日,星期几,当前时间等的显示:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>显示当前时间</title> <script type="text/javascript"> function getTimes(){ var dd=new Date();//获取当前时间对象 var year=dd.getFullYear();//年份 var month=dd.getMonth()+1;//月份+1得到当前月 var day=dd.getDate();//获取日 var ww=dd.getDay();//获取星期 //alert(ww); var weeks=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]; var week=weeks[ww];//根据星期,获取当前星期几; var hour=dd.getHours(); var minutes=dd.getMinutes(); var second=dd.getSeconds(); if(month<10){ month = "0"+month;//判断小于10,前面+0填充 } if(day<10){ day = "0"+day; } if(hour<10){ hour = "0"+hour; } if(minutes<10){ minutes = "0"+minutes; } if(second<10){ second = "0"+second; } document.getElementById("div1").innerText='当前时间'+':'+year+'年'+month+'月'+day+'日'+week+':'+hour+':'+minutes+':'+second; setTimeout("getTimes()",1000);//每秒更新一次 } </script> </head> <body onload="getTimes()"> <div id="times"></div> </body> </html>
效果图如下: