一段显示网站运行时间的代码,保存下来,以备不时之需,也方便有需要的朋友。
时间显示格式:年+天+时+分+秒
Js代码
js代码一般放在<header>标签里面,但为了减少网页加载时间,建议放在页脚文件的</body>前。
<!--网站计时-->
<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(2018, 06, 12, 22, 45, 56)).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>
代码中的 2018, 06, 12, 22, 45, 56 就是网站的正式上线时间。
调用代码
将以下代码放在你希望显示的地方。
<span id="htmer_time" "></span>

