Skip to content
Advertisement

how to get the duration from two dates in the following format

var date2 = new Date(“04/14/2022 12:49:29”)

var date1 = new Date(“04/09/2022 06:16:49”)

I want to get the following duration (“126:32:40 “)

Advertisement

Answer

Try this solution.

Step – 1. Get the time difference between both date

const date1 = new Date("04/09/2022 06:16:49");
const date2 = new Date("04/14/2022 12:49:29");

const diff = date2.getTime() - date1.getTime();

console.log(diff); // Will display 455560000 i.e miliseconds

Step – 2 Convert milliseconds to seconds

let seconds = diff / 1000; // Will return seconds

Step – 3 Convert seconds to Hours

const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600;

Step – 4 Convert Seconds to miniutes

const minutes = parseInt( seconds / 60 ); 
seconds = seconds % 60;

console.log(hours+":"+minutes+":"+seconds)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement