【JS】显示网站运行时间-精确到秒

雨云 RainYun.com 服务器,存储桶,游戏云,域名注册 积分换钱 持证

先亮出JS代码。可以直接放在引用的.js文件里:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function siteTime() {
window.setTimeout("siteTime()", 1000);
var seconds = 1000;
var minutes = seconds * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;
var today = new Date();
var todayYear = today.getFullYear();
var todayMonth = today.getMonth() + 1;
var todayDate = today.getDate();
var todayHour = today.getHours();
var todayMinute = today.getMinutes();
var todaySecond = today.getSeconds();
var t1 = Date.UTC(2022, 6, 1, 0, 0, 0);
var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
var diff = t2 - t1;
var diffYears = Math.floor(diff / years);
var diffDays = Math.floor((diff / days) - diffYears * 365);
var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) / minutes);
var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours - diffMinutes * minutes) / seconds);
document.getElementById("sitetime").innerHTML = diffYears + " 年 " + diffDays + " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
}
siteTime();

直接在html中使用需要在代码前后添加<script></script>
然后在需要显示的地方写上下方代码即可:

1
<span id="sitetime"></span>

如果需要更改显示文本可以在sitetime函数的最后一行的innerHTML=后面修改

更新

最近有人在评论区提出了这段的代码中的许多问题,再此推荐一种更好的实现方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function siteTime(){
window.setTimeout("siteTime()", 1000);
const Jan=0,Feb=1,Mar=2,Apr=3,May=4,Jun=5,Jul=6,Aug=7,Sept=8,Oct=9,Nov=10,Dec=11, today = new Date();
var UseYear = 1;
var t = Date.UTC(2024,Jun,23,00,00,00,000); //GMT Jun 1,2024 00:00:00.000
var diff = today.getTime()-t-today.getTimezoneOffset()*60000;
diff = Math.floor(diff/1000);
var diffSeconds = diff%60; diff = Math.floor(diff/60);
var diffMinutes = diff%60; diff = Math.floor(diff/60);
var diffHours = diff%24; diff = Math.floor(diff/24);
var diffDays = 0, diffYears = 0;
if(UseYear){diffDays = diff%365; diffYears = Math.floor(diff/365);}
else diffDays = diff;
var f = 0, displayString = "";
if(diffYears || f) displayString += diffYears+" 年 ", f=1;
if(diffDays || f) displayString += diffDays+" 天 ", f=1;
if(diffHours || f) displayString += diffHours+" 小时 ", f=1;
if(diffMinutes || f) displayString += diffMinutes+" 分钟 ", f=1;
displayString += diffSeconds+" 秒";
document.querySelectorAll(".sitetime").forEach(function(currentValue){
currentValue.innerHTML = displayString;
});
}
siteTime();

来自:https://blog.air-kevin.rf.gd/2024/JS-SiteTime/

备用:https://web.archive.org/web/20240706031331/https://blog.air-kevin.rf.gd/2024/JS-SiteTime/?i=1


【JS】显示网站运行时间-精确到秒
https://www.yuanzj.top/posts/ec5e389d.html
作者
yzl3014
发布于
2022年6月11日
许可协议