javascriptdatetimeelapsedtime

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


I am trying to compute time elapsed between a set date time object and current time. I want it to be able to appear in this format DD:HH:MM:SS where DD is day, HH is Hours, MM is minutes,SS is Seconds.I am able to get the total day, total hours, total minutes and total seconds but i am not sure how to format it the way I want. Please help

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


Solution

  • I would advise you to use a library like Moment.js, but if you wanted to do this in plain Javascript you could just divide the number of total seconds with the division parameters you already defined and pad them with a zero when they're less than ten.

    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>