1 回答
TA贡献1853条经验 获得超18个赞
我建议您使用像Moment.js这样的库,但是如果您想在纯 Javascript 中执行此操作,您可以将总秒数与您已经定义的除法参数相除,并在它们较少时用零填充它们十个以上。
var myVar = setInterval(myTimer, 1000);
const seconds = 1000;
const minutes = seconds * 60;
const hours = minutes * 60;
const days = hours * 24;
const years = days * 365;
function myTimer() {
const startDateTime = new Date("June 2, 2019 12:36:10 AM");
const newDateTime = new Date();
let elapsedMilliseconds = newDateTime - startDateTime;
document.getElementById("time").innerHTML =
`${formatElapsedTime(elapsedMilliseconds, days)}:${formatElapsedTime(elapsedMilliseconds, hours, 24)}:${formatElapsedTime(elapsedMilliseconds, minutes, 60)}:${formatElapsedTime(elapsedMilliseconds, seconds, 60)}`;
}
function formatElapsedTime(elapsedtime, timeunit, base) {
let time = base ? (elapsedtime / timeunit) % base : elapsedtime / timeunit;
time = Math.floor(time);
time = time < 10 ? '0' + time : time;
return time;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>timer</title>
</head>
<body>
<div id="time" name="timer"></div>
</body>
</html>
添加回答
举报