事先声明:
- 本方法没有考虑到闰年平年
- 月份统一30天计算
所以时间上可能不是很准确,但是相对准确,233
有能力完全可以自定义,我都有注释,中文友好满分。
不多说,上代码
function WebsiteElapsedTime() {
//初始化
this.init = function({
id = "",
time = ""
}) {
if (!id || !time) {
throw new Error("网站已运行时间初始化失败,请传入正确的参数!");
}
const dom = document.getElementById(id);
if (!dom) throw new Error("请传入正确的元素id");
this.dom = dom;
this.time = time;
//首次运行
this.elapsedModifyDom();
//定时器
if (window.$ElapsedTime) clearInterval(window.$ElapsedTime);
window.$ElapsedTime = setInterval(
this.elapsedModifyDom.bind(this),
1000
);
};
//计算时间
this.elapsedTime = function(time = "") {
const startTime = new Date(time.replace("-", "/")).getTime();
const diffTime = Math.floor((Date.now() - startTime) / 1000);
//总天数
const days = Math.floor(diffTime / 86400);
//计算年
const year = days >= 365 ? Math.floor(days / 365) : 0;
//计算月
const month = Math.floor((days % 365) / 30);
//计算天
const day = days - year * 365 - month * 30;
//计算小时
const hours = Math.floor(diffTime / 3600) - days * 24;
//计算分钟
const minutes = Math.floor(diffTime / 60) - days * 1440 - hours * 60;
//计算秒
const seconds =
Math.floor(diffTime) - days * 86400 - hours * 3600 - minutes * 60;
return {
year: {
name: "年",
value: year,
},
month: {
name: "月",
value: month,
},
day: {
name: "天",
value: day,
},
hours: {
name: "小时",
value: hours,
},
minutes: {
name: "分钟",
value: minutes,
},
seconds: {
name: "秒",
value: seconds,
},
};
};
//补零
this.prefixInteger = function(num, length) {
return String(num).padStart(length, "0");
};
//时间显示白名单
this.timeWhitelist = ["seconds"];
//操作dom
this.elapsedModifyDom = function() {
const eTime = this.elapsedTime(this.time);
let infoText = "";
Object.keys(eTime).forEach((key) => {
if (eTime[key].value > 0 || this.timeWhitelist.includes(key)) {
infoText +=
this.prefixInteger(eTime[key].value, 2) + eTime[key].name;
}
});
this.dom.innerHTML = `网站已运行:${infoText}`;
};
}
//使用
new WebsiteElapsedTime().init({
id: "main",
time: "2019-12-06",
});
评论 (0)