Get Time Difference

Calculates the time difference between two dates in the desired unit (e.g., seconds, minutes, hours, days).

Contributed by @itsbrunodev

javascript
function getTimeDifference(date1, date2, unit = "milliseconds") {
  const diff = Math.abs(date2 - date1);
 
  switch (unit) {
    case "seconds":
      return Math.floor(diff / 1000);
    case "minutes":
      return Math.floor(diff / (1000 * 60));
    case "hours":
      return Math.floor(diff / (1000 * 60 * 60));
    case "days":
      return Math.floor(diff / (1000 * 60 * 60 * 24));
    default:
      return diff; // milliseconds
  }
}
javascript
const date1 = new Date("2025-01-01");
const date2 = new Date("2025-01-05");
 
getTimeDifference(date1, date2, "days"); // 4
getTimeDifference(date1, date2, "hours"); // 96
getTimeDifference(date1, date2); // 345600000 (milliseconds)

Keywords

date
difference
time