I have two times like one is 145:02:31 and another one is 01:00:00 and I want to calculate the difference between these two times like 144:02:31 but right now I am getting 13:02:31 which is wrong.
Please help me thank you.
It's a little crude with the formatting but works just the way you need.
function format_ms(time_ms) { let hours = 0; let minutes = 0; let seconds = 0; hours = parseInt(time_ms / 3600000).toString(); time_ms %= 3600000; minutes = parseInt(time_ms / 60000).toString(); time_ms %= 60000; seconds = parseInt(time_ms / 1000).toString(); return hours + ":" + minutes.padStart(2, '0') + ":" + seconds.padStart(2, '0'); } let start = moment.duration('145:02:31'); let end = moment.duration('1:00:00'); let delta_ms = start - end; // in ms console.log(format_ms(delta_ms));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();
It will give you the time difference in hours.
Here a try without any external lib. steps -> 1. convert the timestamp
in seconds
2. calculate diff 3. revert second into desired format
function diff(a, b){
const getSec = val => {
const arr = val.split(':')
return Number(arr[2]) + Number(arr[1])*60 + Number(arr[0])*3600
}
const diff = getSec(a) - getSec(b)
const h = parseInt(diff/3600)
const m = parseInt((diff - h*3600)/60)
const s = diff%60
return`${h}:${m}:${s}`
}
diff("145:02:31", "01:00:00" ) //"144:2:31"
// Convert time in format H:mm:ss to seconds function hrsToSecs(hrs) { var b = hrs.split(':'); return b[0]*3600 + b[1]*60 + +b[2]; } // Convert seconds to time in format H:mm:ss function secsToHrs(secs) { var z = n => (n<10? '0':'') + n; return (secs/3600 | 0) + ':' + z(secs%3600/60 | 0) + ':' + z(secs%60); } // Get different between times in H:mm:ss format // Subtract first time from second function timeDiff(t0, t1) { var diff = hrsToSecs(t1) - hrsToSecs(t0); return (diff < 0? '-' : '') + secsToHrs(Math.abs(diff)); } console.log(timeDiff('1:01:01','0:01:00')) console.log(timeDiff('01:00:00','145:02:31'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.