Difference between two timestamps in hours minutes and seconds

I am trying to calculate the difference between two timestamp “2020-03-18T17:34:45.856Z”, “2020-03-18T16:34:45.856Z” the difference should be like this: 2 hours 20min 30sec

I have tried using

return moment.utc(moment(startDate, 'HH:mm:ss').diff(moment(endDate, 'HH:mm:ss'))).format('HH:mm:ss');

m not sure how to get the desired format

Answer

You need to get it manually using Moment Duration

const startDate = "2020-03-18T17:34:45.856Z";
const endDate = "2020-03-18T16:34:45.856Z";

const diff = moment(startDate).diff(moment(endDate));

const duration = moment.duration(diff);
const hrs = duration.hours();
const mins = duration.minutes();
const secs = duration.seconds();

console.log(hrs + "hours " + mins + "min " + secs + "sec");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *