Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get total hours HH:MM format using Moment.js?

I want to calculate the week total time using Moment.js. Please advise. This is what I tried so far:

total = "00:00";
for (var i in json_obj) {

    var timeEnd = json_obj[i].END;
    var timeStart = json_obj[i].START;

    var timeDiff = moment.utc(moment(timeEnd, "HH:mm:ss").diff(moment(timeStart, "HH:mm:ss"))).format("HH:mm");
    var res = timeDiff;
    total = moment().add(res);

1 Answers

This is what i have achieved with the help of SO and moment.js documentation.

var startTime = moment("06:10:00", 'hh:mm');
var endTime = moment("08:00:00", 'hh:mm');

var totalSec = endTime.diff(startTime, 'seconds');

var hours = parseInt(totalSec / 3600) % 24;
var minutes = parseInt(totalSec / 60) % 60;
var seconds = totalSec % 60;

var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);

The solution is not wholly implemented with moment but combining old school logic with momentjs.

But this will fulfill your requirement.

OR

To remove old school logic and truly go with moment use below code.

var result = moment().startOf('day')
        .seconds(totalSec)
        .format('H:mm')

JSFiddle with both version.

like image 199
J-D Avatar answered Oct 26 '25 22:10

J-D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!