计算经过的时间并将其置于 javascript 中的 Days:Hours:Minutes:Seconds 格式,其中经过的时间每秒更新一次

Calculating time elasped and putting it in Days:Hours:Minutes:Seconds format in javascript where time elapsed updates every second

我正在尝试计算设置的日期时间对象与当前时间之间经过的时间。我希望它能够以这种格式出现 DD:HH:MM:SS,其中 DD 是天,HH 是小时,MM 是分钟,SS 是 Seconds.I 我能够得到总天数、总小时数、总分钟数和总秒数,但我不确定如何按照我想要的方式对其进行格式化。请帮忙

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>timer</title>   
</head>
<body >
<div id ="time" name ="timer"></div>

<script>
var myVar = setInterval(myTimer, 1000);

function myTimer() {

  let seconds = 1000 ;
  let minutes = seconds * 60;
  let hours = minutes * 60;
  let days = hours * 24;
  let years = days * 365;


  const startDateTime = new Date("June 2, 2019 12:36:10 AM");
  const newDateTime = new Date();

  let timeDiff = newDateTime - startDateTime;

  let totalSeconds = Math.round(timeDiff/seconds);


  document.getElementById("time").innerHTML = totalSeconds;
}
</script>

</body>

</html>

我建议您使用像 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 lang="en">

<head>
  <meta charset="UTF-8">
  <title>timer</title>
</head>

<body>
  <div id="time" name="timer"></div>
</body>

</html>