How can I format time durations exactly using Mome

2020-02-05 19:23发布

I would like to do the following, given two dates in UTC formatting:

var start = "2014-01-13T06:00:00.0000000Z";
var end = "2014-01-13T14:16:04.0000000Z";

I would like to get the exact time span that passes between these two times, such as

8h 16m

I have tried using the following:

var duration = moment(moment(end) - moment(start)).format('hh[h] mm[m]');

But this does not work with days. Moreover, it does not work with days, since they are always >=1 even if <24 hours pass.

I have also tried twix.js to get the length, but its formatting doesn't support creating the format specified above, or I could not find the way to do so in its documentation. Basically I am looking for an exact version of twix.humanizeLength().

Moment.js's a.diff(b) provides only total durations, it can give me the length of the time span in minutes, hours or days, but not calculated using remainders.

My current solution is to use diff to create the ranges and then use modulo to calculate remainders, but this is not very elegant:

var days = moment(end).diff(start, 'days');
var hours = moment(end).diff(start, 'hours') % 24;
var minutes = moment(end).diff(start, 'minutes') % 60;

var duration = ((days > 0) ? days + 'd ' : '') + ((hours > 0) ? hours + 'h ' : '') + ((minutes > 0) ? minutes + 'm ' : ''); 

The question: Is there any smarter way to do this in either moment.js or twix.js, or should I take my time and develop my own moment.js plugin?

2条回答
狗以群分
2楼-- · 2020-02-05 19:40

You can try using Durations, but I'm not sure if those have the capabilities you are looking for http://momentjs.com/docs/#/durations/

Also, you can always user moment's diff to get the difference in milliseconds and then format it to your needs. It is basically the same that you are doing, but you only call diff once.

function convertMilliSecondsIntoLegibleString(milliSecondsIn) {

    var secsIn = milliSecondsIn / 1000;
    var milliSecs = milliSecondsIn % 1000;

    var hours = secsIn / 3600,
    remainder = secsIn % 3600,
    minutes = remainder / 60,
    seconds = remainder % 60;


    return ( hours + "h: "
            +  minutes + "m: "
            + seconds +"s: " + milliSecs + "ms");
}
查看更多
可以哭但决不认输i
3楼-- · 2020-02-05 19:54

There's a plugin for formatting duration in moment.js : moment-duration-format

If it doesn't do what you need, then you should extend moment.duration.fn. If you don't support many locales, it should be easy enough.

In any case, I'd recommend to read the thread of this feature request.

查看更多
登录 后发表回答