计算经过的时间并将其放入 javascript 中的 Days:Hours:Minutes:

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


<!DOCTYPE html>

<html>

<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>


潇潇雨雨
浏览 155回答 1
1回答

慕容森

我建议您使用像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() {&nbsp; const startDateTime = new Date("June 2, 2019 12:36:10 AM");&nbsp; const newDateTime = new Date();&nbsp; let elapsedMilliseconds = newDateTime - startDateTime;&nbsp;&nbsp;&nbsp; document.getElementById("time").innerHTML =&nbsp;&nbsp; `${formatElapsedTime(elapsedMilliseconds, days)}:${formatElapsedTime(elapsedMilliseconds, hours, 24)}:${formatElapsedTime(elapsedMilliseconds, minutes, 60)}:${formatElapsedTime(elapsedMilliseconds, seconds, 60)}`;}function formatElapsedTime(elapsedtime, timeunit, base) {&nbsp; let time = base ? (elapsedtime / timeunit) % base : elapsedtime / timeunit;&nbsp; time = Math.floor(time);&nbsp; time = time < 10 ? '0' + time : time;&nbsp; return time;}<!DOCTYPE html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <title>timer</title></head><body>&nbsp; <div id="time" name="timer"></div></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript