Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - How can I format time durations exactly using Moment.js?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...