How to calculate time duration in same day?

I want to get time duration in given time (“1970-01-01T12:21:19.000Z” - MSSQL time format) and current time. In same date (ignore the date).

Example :-
Given time = 12:25
Current Time = 14:30
Output = 2h 05min

Well, there are libraries, like moment.js that will do that for you.

If you want to do it yourself, I I would use the JS Date module to convert the to UTCs (the number of milliseconds since January 1, 1970). With that you can subtract them and do a little math to generate whatever output string you want.

``````function timeDiffCalc(dateFuture, dateNow) {
let diffInMilliSeconds = Math.abs(dateFuture - dateNow) / 1000;

// calculate days
const days = Math.floor(diffInMilliSeconds / 86400);
diffInMilliSeconds -= days * 86400;
console.log('calculated days', days);

// calculate hours
const hours = Math.floor(diffInMilliSeconds / 3600) % 24;
diffInMilliSeconds -= hours * 3600;
console.log('calculated hours', hours);

// calculate minutes
const minutes = Math.floor(diffInMilliSeconds / 60) % 60;
diffInMilliSeconds -= minutes * 60;
console.log('minutes', minutes);

// calculate secounds
var secd = ~~diffInMilliSeconds % 60;
var seconds = Math.ceil(secd);

let difference = '';
if (days > 0) {
difference += (days === 1) ? `\${days} day, ` : `\${days} days, `;
}

difference += (hours === 0 || hours === 1) ? `\${hours} hour, ` : `\${hours} hours, `;

difference += (minutes === 0 || hours === 1) ? `\${minutes} minutes ` : `\${minutes} minutes `;

difference += ( hours === 1 || minutes === 1 ) ? `\${seconds} secounds` : `\${seconds} secounds`;

return difference;
}

const z = '2020/05/05'
const w = '13:12:00'
const l = '2020/05/05'
const o = '14:13:56'
const x = `\${z} \${w}`
const y = `\${l} \${o}`

const a = timeDiffCalc(new Date(x), new Date(y))
console.log(a);

``````
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.