Get time difference in hh: mm between two dates using moment

I have a problem getting the time difference between two timestamps (epoch format).

I used moment().format("L LT")

to convert it to my desired time format (t21>), but now the problem is that I want the time difference inhh:mm

PS: it could be more than 24 hours.

What I have tried:

let timeDiffms,duration,timedifference,
start moment(startTimeStampInMS).format("L LT"),
end = moment(endTimeStampInMS).format("L LT");

timeDiffms = moment(end, "MM/DD/YYYY HH:mm").diff(moment(start, "MM/DD/YYYY HH:mm"));
duration = moment.duration(timeDiffms);
timedifference = Math.floor(duration.asHours()) +":"+duration.minutes();  // result

//output I am getting  
// start = "03/20/2017 3:11 PM" end="03/21/2017 9:45 AM" timedifference = "30:24", (incorrect)
// start = "03/20/2017 10:07 AM" end="03/23/2017 11:24 AM" timedifference = "73:17" (correct)
// start = "03/20/2017 3:11 PM" end="03/23/2017 11:31 AM" timedifference = "80:20" (incorrect) strange 


I don't know what's going on here.


source to share

2 answers

Based on the previous answer, I was able to work around this logic and get the correct solution for my question.

let start moment(startTimeStampInMS),
end = moment(endTimeStampInMS);

let timediffms = end-start;    // difference in ms
let duration = moment.duration(timediffms);
 // _data should not be used because it is an internal property and can 
 //change anytime without  any warning 
//let hours = duration._data.days*24 + duration._data.hours; 
//let min = duration._data.minutes;
let hours = duration.days()*24+ duration.hours();
let min = duration.minutes();
timeDifference = hours +":"+ min;  // Answer




In your current solution, you format the object as a string and then parse the string until you get it diff

. You don't need to follow this two-step process, you can do the following to get the duration:

start moment(startTimeStampInMS),
end = moment(endTimeStampInMS).format("L LT");

timeDiffms = end.diff(start);
duration = moment.duration(timeDiffms);


Or, since your input is in milliseconds:

moment.duration(endTimeStampInMS - startTimeStampInMS);


To get duration

in the format HH:mm

, you can use the duration-format module , which adds a format

method to the duration object.

Here's a working example:

// Example milliseconds input
let startTimeStampInMS = 1490019060000;
let endTimeStampInMS = 1490085900000;
// Build moment duration object
let duration = moment.duration(endTimeStampInMS - startTimeStampInMS);
// Format duration in HH:mm format
console.log( duration.format('HH:mm', {trim: false}));

<script src=""></script>
<script src=""></script>

Run codeHide result



All Articles