今天逛网站,偶然发现博友博客网站底部会显示本站稳定运行XX年XX天XX时XX秒,并且秒数在动态变化,个人还是比较喜欢这东西的,所以测试了下代码,并应用于本站。分享给大家,有需要的朋友直接修改下日期然后Copy过去使用即可。
如果需要显示运行时间:XX年XX天XX时XX秒,秒数还是动态的,请选用下面的代码(具体效果参加本站底部):
<span id="htmer_time"> <script> function secondToDate(second) { if (!second) { return 0; } var time = new Array(0, 0, 0, 0, 0); if (second >= 365 * 24 * 3600) { time[0] = parseInt(second / (365 * 24 * 3600)); second %= 365 * 24 * 3600; } if (second >= 24 * 3600) { time[1] = parseInt(second / (24 * 3600)); second %= 24 * 3600; } if (second >= 3600) { time[2] = parseInt(second / 3600); second %= 3600; } if (second >= 60) { time[3] = parseInt(second / 60); second %= 60; } if (second > 0) { time[4] = second; } return time; }</script><script type="text/javascript" language="javascript"> function setTime() { var create_time = Math.round(new Date(Date.UTC(2016, 08, 08, 10, 11, 12)).getTime() / 1000); var timestamp = Math.round((new Date().getTime() + 8 * 60 * 60 * 1000) / 1000); currentTime = secondToDate((timestamp - create_time)); currentTimeHtml = '本站已安全运行:' + currentTime[0] + '年' + currentTime[1] + '天' + currentTime[2] + '时' + currentTime[3] + '分' + currentTime[4] + '秒'; document.getElementById("htmer_time").innerHTML = currentTimeHtml; } setInterval(setTime, 1000);</script>
上面代码中“2016,08,08,10,11,12”是指的建站时间,分别对应年、月、日、时、分、秒,根据自己实际修改即可。
如果只需要显示运行天数:XX天,这个比较简单,请选用下面的代码:
本站已安全运行<b><strong><script language = "JavaScript"type = "text/javascript" >var urodz = new Date("12/19/2014");var now = new Date();var ile = now.getTime() - urodz.getTime();var dni = Math.floor(ile / (1000 * 60 * 60 * 24));document.write( + dni)</script></strong></b>天
显示当前时间的代码如下(具体效果请参见原站左上角):
<script type="text/javascript">var timer = null, divText = document.getElementById("clock"); showTime(); timer = setInterval(showTime,1000);function showTime(){ var today = new Date(); var date = today.getDate(); var day = today.getDay(); var month = today.getMonth()+1; var year = today.getFullYear(); var hour= addZero(today.getHours()); var min = addZero(today.getMinutes()); var sec = addZero(today.getSeconds()); var week=""; if (true) {}; if (day==0) week='星期日'; if (day==1) week='星期一'; if (day==2) week='星期二'; if (day==3) week='星期三'; if (day==4) week='星期四'; if (day==5) week='星期五'; if (day==6) week='星期六'; divText.innerHTML = "当前时间:"+year+"年"+month+"月"+date+"日 "+ week +" "+"("+hour + ":"+ min + ":"+sec +")";}function addZero(num){ if (num <= 9) { return "0"+num; }else { return num; }}
把上面代码复制到网页文件中,然后在你想显示的地方添加如下代码即可(请注意修改颜色配置):
<span id="clock" style="color: #aaa;"></span>