1

I am trying to get the time that has happened between two dates. Example:

oldDate = "4/16/2020, 12:00:00"

today = "5/17/2021, 1:00:50"

Result that a need:

years = 1

months = 1

days = 1

hours = 1

minutes = 0

seconds = 50

I also would like to refresh it every second, so that, the user can see it running. Thanks.

  • Does this answer your question? [How to calculate date difference in JavaScript?](https://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript) – Sysix Jul 16 '21 at 20:09

1 Answers1

3

Use Date.parse() to get a Date object from a string, subtract two dates using the - operator, and get the number of years, months, days, etc. using the corresponding methods. Then use setInterval to run it every second, and Date.now() to get the current time.

const oldDate = Date.parse("4/10/2020, 12:00:00");

// weird but seems to work with all dates 
const getYear = (date) => date.getFullYear() - 1970;
const timeBetweenDates = (date1, date2) => {
  const date = new Date(date1 - date2);
  return {
    years: getYear(date),
    months: date.getMonth(),
    days: date.getDay(),
    hours: date.getHours(),
    minutes: date.getMinutes(),
    seconds: date.getSeconds(),
  }
}
const pre = document.getElementById("display");
setInterval(() => {
  pre.textContent = JSON.stringify(
    timeBetweenDates(Date.now(), oldDate),
    0, 
    2
  );
}, 1000);
<pre id="display">Wait a second...</pre>