Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting MomentJS duration above 24 hours

I would like to format a summed up total working hours e.g. 49.75 to this: 49:45.

When I use duration like this:

const dur = moment.duration(49.75, 'hours').asMilliseconds();
moment.utc(dur).format("HH:mm:ss") // 01:45:00

I'll receive 01:45:00 instead of 49:45:00

Is there a way to format (instead of HH) duration without dropping the days?

like image 543
DoK Avatar asked Aug 11 '17 07:08

DoK


People also ask

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.


2 Answers

I think you cannot use format but build it manually:

var dur = moment.duration(49.75, 'hours');
var hours = Math.floor(dur.asHours());
var mins  = Math.floor(dur.asMinutes()) - hours * 60;
var sec   = Math.floor(dur.asSeconds()) - hours * 60 * 60 - mins * 60;

var result = hours + ":" + mins + ":" + ((sec > 9) ? sec : ("0"+sec));
console.log(result); // 49:45:00

Fiddle


Hope someone will find more elegant way

like image 159
Maxim Shoustin Avatar answered Sep 28 '22 04:09

Maxim Shoustin


I recommend you this answer.

You can add a format for the duration, and it works for greater than 24 Hour.

function(input) {
    input = input || '';
    var out = '';
    var dur = moment.duration(input, 'minutes');
    return dur.format('HH:mm:ss');
};

I hope it can help you!

EDIT:

This code uses duration-format plugin!

like image 40
LakiGeri Avatar answered Sep 28 '22 04:09

LakiGeri