Moment: duration formatting

Created on 5 Sep 2013  ·  118Comments  ·  Source: moment/moment

We've touched on this before in #463 and #879 but never really talked about it directly in its own issue.

We need a method for formatting durations similar to how we format dates. It should be as simple as:

moment.duration(x).format("H:mm:ss")

Note that the formatting tokens would have to carry slightly different meaning, since we're representing an elapsed duration of time, rather than a time-of-day. I suggest the following:

  • hh would mean "hours remainder after accounting for days"
  • h would be the single digit form of hh
  • HH would mean "total whole hours"
  • H would be the single digit form of HH
  • HHH would mean "total hours including decimals" - although that can currently be done with duration.asHours(), so this might not be necessary.

Similar formatting would apply for other units. In this context, the highest unit would be a "day", which would be a standard day consisting of 24 standard hours. It wouldn't make sense to measure years or months with this due to calendaring issues.

Note, this came up recently (again) on StackOverflow in this question. The user was looking for something like duration.format("H:mm:ss"). This is the workaround:

Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")

This works, but it feels hacky. This should be built in.

New Feature Up-For-Grabs

Most helpful comment

Isn't it better to do

moment.utc(total.asMilliseconds()).format("HH:mm:ss");

instead of

Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")

All 118 comments

+1

moment.duration(x).format("H:mm:ss") was exactly what I was expecting, before understanding that it would not work. The workaround suggested by Matt worked fine but comparing with the elegance of other things in momentjs it sure seems hacky.

Isn't it better to do

moment.utc(total.asMilliseconds()).format("HH:mm:ss");

instead of

Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")

Code Bounty

@RobinvdVleuten - The problem with using the HH in the current formatter is that it represents the hour _portion_ of a full date and time. When dealing with an _elapsed_ time, there could well be 24 hours or more. Try passing 24 hours in, and you'll see that it gets reset to zero.

I noticed it indeed. I'm now using the calculated milliseconds to format it, but it's still a hacky workaround.

Are you thinking there will just be one "level" of remaindering possible--e.g. no way to say "hours after accounting for months"? I think that's a perfectly reasonable limitation, but just to spitball a sec, I could imagine providing an "anchor" argument, like so:

moment.duration(x).format("hh:mm:ss", "M");

Which tells us that the hours should be modulo the month. The anchor is optional and would default to the largest unit plus one size up (in this case, days). Similarly, it could use the string itself to determine that the minutes are modulo the hours and seconds modulo minutes. Whereas if you did this:

moment.duration(x).format("hh:ss");

...the seconds would be modulo the hours.

That's probably all not a great idea--it's not ironed out (where to weeks go in this hierarchy?) and it's probably unnecessary (people are unlikely to want holes like that). But fun to think about.

On a more serious note, how are you going to deal with month vs minutes with this lowercase/uppercase notation?

I was envisioning that days would be the maximum unit size, so months wouldn't enter the picture. Basically, this is the inverse of how we parse durations coming from asp.net time spans.

Makes sense.

I have been reading a SCORM 2004 RTE (p77) document, and i found that for time interval representation is as follows, i think this came from a standar,

in theory i can pass a value like: P34H
and the parsers should interpret that as 1day and 10 Hours

i hope it could be posible to format the ouput with this in mind
like 'PHM'
and the formatter interpret that as total Hours remaining minutes?
i would like to be able to format the output like HH:MM

i hope this info is helpfull

timeinterval (second, 10,2):The timeinterval (second, 10, 2)denotes that the value for
the data model element timeinterval represents elapsed time with a precision of 0.01
seconds[1]. The SCORM dot-notation binding defines a particular format for a
characterstring to represent a timeinterval.
The format of the characterstring shall be as follows:
P[yY][mM][dD][T[hH][nM][s[.s]S]] where:
• y: The number of years (integer, >= 0, not restricted)
• m: The number of months (integer, >=0, not restricted)
• d: The number of days (integer, >=0, not restricted)
• h: The number of hours (integer, >=0, not restricted)
• n: The number of minutes (integer, >=0, not restricted)
• s: The number of seconds or fraction ofseconds (real or integer, >=0, not
restricted). If fractions of a second are used, SCORM further restricts the string to
a maximum of 2 digits (e.g., 34.45 – valid, 34.45454545 – not valid).
• The character literals designators P, Y, M, D, T, H, Mand Sshall appear if the
corresponding non-zero value is present.
• Zero-padding of the values shall be supported. Zero-padding does not change the
integer value of the number being represented by a set of characters. For
example, PT05H is equivalent to PT5H and PT000005H.
Example:
• P1Y3M2DT3H indicates a period of time of 1 year, 3 months, 2 days and 3 hours
• PT3H5M indicates a period of time of 3 hours and 5 minutes

Implementers should be aware that the format and binding is for the communication of
the data between a SCO and an LMS. Since the format is representing a period of time,
then a duration like PT5M is equivalent to PT300S.
If the data model element, that is of type timeinterval(second,10,2) contains a value, then
• The designator Pshall be present;
• If the value of years, months, days, hours, minutes or seconds is zero, the value
and corresponding character literal designation may be omitted, but at least one
character literal designator and value shall be present in addition to the designator
P;
• The designator Tshall be omitted if all of the time components (hours, minutes
and seconds) are not used. A zero value may be used with any of the time
components (e.g., PT0S).

Duration formatting would be an excellent addition. There's no need for two distinct "hour" tokens. Assume a duration of 32 hours. You'd never want to extract just 8 hours without also extracting 1 day.

I think @icambron has a good suggestion. Parse the format string into tokens and express the duration in terms of the largest unit. Parse the tokens one at a time in order (e.g., "DD:hh:ss" meaning number of complete days, number of complete hours after accounting for days, number of complete seconds after accounting for days + hours).

I've posted a moment.duration.format plugin:
https://github.com/jsmreese/moment-duration-format

I think it addresses most of the ideas / use-cases in this thread.

@jsmreese Have you consider filing a pull request that contains your plugin as a core part of momentjs?

@hotzenklotz Yes I have considered filing a pull request.

I haven't done so because of all the reasons @icambron laid out in #1538.

My plugin:

  • depends on Lo-Dash
  • does not look and feel like Moment.js code
  • uses a completely different test setup

I would _love_ for my plugin to become part of Moment.js core... but I'm not going to waste their time with a pull request before those issues are addressed.

We would also want to make sure that the code can be internationalized. Fortunately, most of the strings we would need are in the Unicode CLDR, so very little translation work should be necessary.

The CLDR also has locale-specific recommendations on how to format certain kinds of intervals, which could potentially be more useful than arbitrary duration formats. Not sure how that fits in here, but it may be nice to automagically be able to display locale-specific intervals between two specific times.

The CLDR also has information about how to display specific time intervals (rather than durations) which could be useful at some point...

English(US) Calendar Data

Just published a new version of Moment Duration Format that removes the previous dependency on Lo-Dash or Underscore.

https://github.com/jsmreese/moment-duration-format

@jsmreese Suits our needs perfectly. Thanks!

+1

+1

+1

+1

+1

+1

+1

+1

I probably sound like a broken record on this issue, but I would like to ensure that any solution follows existing conventions wherever possible, and can easily be internationalized (which includes adding symbols similar to LLLL for commonly-used duration formats.

Somewhat annoyingly, the CLDR doesn't provide many specific guidelines for formatting durations, although there are extensive relative duration and interval guidelines which could be of use to moment elsewhere. However, they do provide some minimal guidelines and translations for duration units, which would allow you to concatenate the relevant units when implementing something like humanize().

The hh / h syntax described above feels like a significant departure from the formatting tokens used by ISO8601, CLDR, and Apache, and I would prefer to avoid it if at all possible.

A better proposal might be to infer to use the most significant unit in the formatting pattern as the modulo, so h:mm:ss would display a "normal" time, but count hours past 24 (eg 26:30:00). It's unclear how one would even compute a pattern like "HH:MM:ss", or what the use case for that would be. Allowing developers to override this behavior also seems like it could easily become a source of bugs.

Keeping in the spirit of "i18n everywhere," the CLDR defines duration formats for:

  • Hours + minutes ( h:mm in EN-US)
  • Hours + minutes + second (h:mm:ss in EN-US)
  • Minutes + seconds (m:ss in EN-US)
    and it might make sense to provide locale-specific constants (similar to the LLL date formats) for these time durations.

Unfortunately, formatting durations with units greater than hours is really difficult to express via a single formatting string (thanks to the pluralization rules that you'd need to consider), and I wasn't able to find _any_ library in any language that allows for easy, i18n-friendly formatting of durations longer than 24 hours. The best that you can do would be to extend duration.humanize() to take some extra parameters, effectively implementing the original proposal in #463.

In short, it might not be a good idea to implement duration.format(), as I see any potential solution having considerable pitfalls. Your best bet would be to improve duration.humanize(), or implement a scaled-back duration.format() that only understands hours, minutes, and seconds.

+1

In case you need a quick function to add padding:

function padWithZero(input, length) {
    // Cast input to string
    input = "" + input;

    let paddingSize = Math.max(0, length - input.length);
    return new Array(paddingSize > 0 ? paddingSize + 1 : 0).join("0") + input;
}

+1

+1

+1

+1

+1

+1

+1

+1

+1

+1

+1

:+1:

:+1: surprised moment doesn't do this, usually it's never failed me!

+1 I have used moment-duration-format, noted above, but it is not internationalized. I am trying to output days and am likely to need months as well, which really need labels.

Is there any progress with this issue?

+1

+1

+1

+1

:+1:

+1
why is it still not in the core?

+1 +1 +1 +1 +1

+1

+2

@jsmreese does ur plugin support i18n?

@rumeshwick: maybe? That really depends on how you're doing i18n and what you're expecting from my plugin.

+1

I found out that it's possible in this kind of hacky way:

  var dur = moment.duration('PT90M');
  moment(dur._data).format('[it\'s] D [days and] h [hour]');

This yields:

"it's 1 days and 1 hour"

You can not, however, print something like "it's 1 days and 90 Minutes".
For my purposes this is enough.
It does not include i18n but in my case I don't want this to be solved by moment.js.

Hi have an Ember.JS helper over here for this:

https://github.com/ember-building-blocks/ember-hbs-date-helpers

+1

+1 for the hacky way of @vanthome :+1:

@jsmreese - would you be interested in merging your plugin into moment core? It would be very useful, and much appreciated.

It would need to be reformatted to fit the new ES6 implementation, and have some redundant functions replaced with moment's equivalent, but overall I think it would be fairly easy.

@mj1856 definitely interested. I'll ping you over email with a few questions.

Yay! Way to go, @jsmreese and @mj1856!!! :clap: :clap: :clap:

I came here just to propose to merge @jsmreese's plugin to moment js.

+1

+1

Since it looks like @jsmreese is short on time, I'm marking this as Up For Grabs. Essentially, the proposed PR should implement all of the functionality of @jsmreese's moment-duration-format plugin, but should conform to the ES2015 style now being used in moment.js, and should re-use as much of the existing moment.js functionality to minimize code size.

+1

One feature that @jsmreese's moment-duration-format plugin lacks, is the ability to construct back a duration object from the formatted string.

hey @mj1856 , i'm interested in tackling integrating the format plugin into moment. how does contributing work here with the Up-For-Grabs label, should I just work on it and submit the PR to the develop branch, or has someone else claimed it?

@joshrowley it's not claimed, but you would be a hero if you got it done. Go ahead and take it, and when you're ready submit a pull. This one will be a little trickier than other up for grabs, so if you want to, feel free to submit a pull request for review before you are done - we'll keep an eye out for it. We will be picky about not exploding the size of the library with this one - it's already bigger than we would like. Please be mindful of that.

Maybe I'll handle this as well (or instead), but first need to fit into whole moment dev structure.

Work in progress PR: #3308

Hi folks, I opened a PR at #3615 and would love some eyes on it!

perhaps this is related - issues encountered:
moment.duration(3500000).format("hh:mm", { forceLength: true })
which displays result : 58, rather than 00:58

http://stackoverflow.com/questions/41443233/using-moment-js-to-display-duration-in-format-00xx-when-duration-is-less-than-a

ms = moment(moment().format(),"YYYY-MM-DD HH:mm:ss").diff(moment(time,"YYYY-MM-DD HH:mm:ss"));
var duration = moment.duration(ms);
moment(duration._data).format("HH:mm");

Yet another hack to format durations....

var timeInSeconds = 5000;
var formattedDur = moment("1900-01-01 00:00:00").add(timeInSeconds, 'seconds').format("HH:mm:ss");

+1

Note that the hacks posted by @fabiogalera and @befreestudios seem to work well for durations < 24 hours, but neither works for durations longer than 24 hours.

EDIT: This appears to be due to being on an older version of moment. I just tried it again with the latest version and it works as expect. Sorry for the confusion.
-
I also have found some weird rounding errors/edge cases with the original hack posted by @mj1856 at the top of this thread. For example, try 2.3 or 4.1 hours. Those are decimal values which should divide evenly into a number of minutes.

For example, 2.3 should be exactly 2:18:00 but you'll get 2:17:59. And 4.1 should be exactly 4:06:00, but you'll get 4:05:59. This seems to be due to the duration.asXXX() methods having some precision/rounding issues. Has anyone else seen this and have any suggestions?

Here is my funtion for duration.format based on Date.format (https://gist.github.com/ptquang86/2893903)

moment.duration.fn.format = moment.duration.fn.format || function (mask): string {
            // Some common format strings
            let formatMasks = {
                "default":      "DD MM YYYY HH:mm:ss",
                shortDate:      "M/D/YY",
                mediumDate:     "MM DD, YYYY",
                longDate:       "MM DD, YYYY",
                fullDate:       "DD, MM, YYYY",
                shortTime:      "H:mm TT",
                mediumTime:     "H:mm:ss TT",
                longTime:       "H:mm:ss TT Z",
                isoDate:        "YYYY-MM-DD",
                isoTime:        "hh:mm:ss",
                isoDateTime:    "YYYY-MM-DD'T'hh:mm:ss",
            };

            let format = function () {
                let token = /D{1,2}|M{1,2}|YY(?:YY)?|([HhmsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g;

                function pad(val, len?) {
                    val = String(val);
                    len = len || 2;
                    while (val.length < len) val = "0" + val;
                    return val;
                }

                // Regexes and supporting functions are cached through closure
                return function (date, mask) {
                    mask = String(formatMasks[mask] || mask || formatMasks["default"]);

                    let D = date.days(),
                        m = date.months(),
                        y = date.years(),
                        H = date.hours(),
                        M = date.minutes(),
                        s = date.seconds(),
                        L = date.milliseconds(),
                        flags = {
                            D:    D,
                            DD:   pad(D),
                            M:    m + 1,
                            MM:   pad(m + 1),
                            YY:   String(y).slice(2),
                            YYYY: y,
                            H:    H % 12 || 12,
                            HH:   pad(H % 12 || 12),
                            h:    H,
                            hh:   pad(H),
                            m:    M,
                            mm:   pad(M),
                            s:    s,
                            ss:   pad(s),
                            l:    pad(L, 3),
                            L:    pad(L > 99 ? Math.round(L / 10) : L),
                            t:    H < 12 ? "a"  : "p",
                            tt:   H < 12 ? "am" : "pm",
                            T:    H < 12 ? "A"  : "P",
                            TT:   H < 12 ? "AM" : "PM",
                        };

                    return mask.replace(token, function ($0) {
                        return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
                    });
                };
            }();

            return format(this, mask);
        };

use: moment.duration(10000).format("hh:mm:ss:l")

+1

Any news here, will moment get this functionality? What's the consensus?

+1

Bumping again it's like the 4th project where I wanted to use such a function. I hope to see it implemented in moment.js very soon.

+1

I've been keeping an eye on this for a long time hoping that this feature will get implemented. Is there any work in progress on this?

As far as i know it is working right now, i have it in my app, check the docs:
https://momentjs.com/docs/#/durations/

@luchillo17 Are you talking about durations, in general, working?

Well i just tried 5 mins back and it was working.

Well, just wanted to be clear about what we're talking about here. Durations _do_ work. This issue is about the formatting of durations.

My bad, the thread is that big that i got lost in the way down.

However now that i look closer there's a plugin for moment duration formatting listed in the docs:
https://momentjs.com/docs/#/plugins/duration-format/

Is that what you guys hoping for? seems like it even has TypeScript type definitions.

And i've tested it, works pretty good.

The plugin works very well. Would love to see it merged into Moment.js. I can't see how durations are useful without it.

It is a plugin because not all people uses duration, i don't see that much of an user base needing durations to justify making the code base bigger.

I'm even surprised the whole duration module isn't in a plugin.

Or that. Currently, the duration module is pointless to me. All the functions in it are just simple math that can be done just fine without a library.
If the plugin was merged, then I can see it having a good use.

Maybe, but not thinking in that math is what libraries are good for, battle tested solutions so you and i don't have to waste time on such tasks, like for example i didn't know there were so many standards for duration, like ISO 8601, the durations module takes care of that for me so i don't need to know how that standard is defined.

I guess so.
Either way, I propose we reference the plugin in the documentation.
That way, people know the functionality is there, and don't have to take out to Google and search for this functionality.

Indeed, took me some while to find out the plugin section for it.

4 years and still no reaction from owners... That's sad :(

Hi folks,

This is something we're still working on. Moment is a volunteer community! We need to make sure a feature like this has these properties:
1) works in every environment
2) doesn't add too much bulk to the code
3) doesn't re-invent the wheel (i.e. there's already a plugin to do this!)
4) doesn't break existing features

It's possible this will merge at some point.
https://github.com/moment/moment/pull/3615

If you think the docs could better point to the duration formatting plugin (or other plugins!), please send a PR our way here: https://github.com/moment/momentjs.com/

@marwahaha

doesn't add too much bulk to the code
doesn't re-invent the wheel (i.e. there's already a plugin to do this!)

Well, since there is already duration-format plugin and duration inside moment library, maybe the best solution is to take out duration from moment.js into separate plugin and then implement all the "heavy" stuff inside that plugin?
By doing so 2 goals will be achieved:
1) decrease moment.js size
2) provide duration directly with the most useful features instead of very limited version.

One large challenge is that duration formatting will be very difficult to implement across the full range of locales that moment.js supports.

I'd hate to see those locales lose the limited duration support that they currently have, or for Moment to add a feature that only works correctly in some locales. Keeping duration formatting in a plugin seems like a good middle-ground that ensures that the "core" of moment.js is stable, and works for everyone, while giving single-locale users the option to use plugins that perform functions specific to their locale.

The duration formatting plugin already exists and is referenced inside the documentation. Thats more than enough.

@OogieBoogieInJSON Well, the docs aren't that helpful, i basically had to check this issue before even getting to the plugins in the docs, there's little exposure to those features unless you actually try and read the whole docs, which admittedly nobody does.

@luchillo17 I do read all the docs before working with anything. Probably, thats just me.

Haha, yeah, it's great that you do, everyone should, but most of us as devs have schedules to meet, so understanding every nut & bolt of all libs we use isn't practical.

@luchillo17 It's not the documentation's fault you do Management Oriented Programming. Cheers!

For those following the saga of formatting moment durations, I've published version 2.0.0 of my moment-duration-format plugin.

The new version resolves/incorporates almost all the issues and feedback from the past four years version 1 has been in the wild -- including localization and pluralizing support as well as some useful formatting options.

Check it out here: https://github.com/jsmreese/moment-duration-format/releases

The real MVP -> @jsmreese

Hah. Thanks for the kind words, @OogieBoogieInJSON.

I can't help but note that my plugin stands on top of -- and wouldn't exist without -- the huge efforts of moment's creators and maintainers, not to mention the many, many contributors. My taking the time now to revisit something I created four years ago (wow, has it really been that long!) quite frankly pales in comparison to their continuous shepherding of this project!

Aaaaaand version 2.1.0 is published.
https://github.com/jsmreese/moment-duration-format/releases

Updated version fixes a few issues from version 2.0, and introduces moment.duration.format, a new function for coordinated formatting of multiple durations. Not to be confused with the already-existing moment.duration.fn.format.

The new function takes an array of durations, and returns an array of formatted strings, and is useful whenever you have a group of durations that must be formatted together in a consistent manner.

moment.duration.format([
    moment.duration(1, "second"),
    moment.duration(1, "minute"),
    moment.duration(1, "hour")
], "d [days] hh:mm:ss");
// ["0:00:01", "0:01:00", "1:00:00"]

moment.duration.format([
    moment.duration(1, "minute"),
    moment.duration(1, "day")
], "w [weeks], d [days], h [hours], m [minutes], s [seconds]", { trim: "all" });
// ["0 days, 1 minute", "1 day, 0 minutes"]

@jsmreese 2.0 did lead to some errors earlier so I had to lock it to 1.3.0 for safety, nevertheless thank you for keeping the feature/project alive.

@prusswan please do give version 2.1.0 a try. I'd like to know if you still see those errors!

I've published version 2.2.0 of moment-duration-format, which now includes a fallback number format function because toLocaleString is not fully implemented in many environments.

https://github.com/jsmreese/moment-duration-format/releases

I've tested the new version using BrowserStack on a range of Android devices with OS versions from 2.2 to 7, and on a range of iOS devices with OS versions from 4.3 to 11. Also tested on Chrome, Firefox, IE 8-11, and Edge browsers.

@prusswan and others who had to lock the version to 1.3.0, you'll likely find that version 2.2.0 is finally the drop-in replacement that version 2.0.0 was supposed to be.

Thank you to all who have logged issues against version 2 of this plugin!

Having implemented version 2 of the moment-duration-format plugin, there are some obvious improvements for a version 3.

I've listed my ideas below and added them as issues on the repository. If you have ideas or comments about what you'd like to see, please let me know!

Hopefully the next version will be published in something like 4 months... not the 4-year wait for version 2.

  • The fallback number formatting localization options should be included with the Moment Locale object extensions I've already made for localizing duration unit labels. This would put all of the localization configuration in one place.

  • moment-duration-format and its fallback number formatting function do not follow the same API as Number#toLocaleString for significant digits and faction digits. The fallback function should be updated to use the toLocaleString API, and the plugin should expose the toLocaleString API options directly rather than hiding some of the options and masking them behind precision and useSignificantDigits options.

  • Exposing the fallback number formatting function as well as the toLocaleString feature test function would facilitate testing and allow them to be used outside of the context of formatting durations.

  • Add type definitions to support TypeScript, publish NuGet package, and support whatever other packaging options are in use these days. (This doesn't have to wait until version 3.)

  • Testing of the plugin should be modernized, ideally to match the Moment.js testing setup. (This doesn't have to wait until version 3, either.)

@jsmreese Tremendous work, but totally don't feel pressured to bump the major version twice within a short period of time. If it is still in use after 4 years without an update, then it is probably mostly good enough. I feel this current issue can be closed since there is already a resolution (use the plugins). A new issue can be started to decide if this functionality should become part of moment itself.

@jsmreese Amazing. Thank you so much and just in time! Huge deal for me and thank you for all that you do.

See https://momentjs.com/docs/#/-project-status/

Thanks for all the discussion here.

Was this page helpful?
0 / 5 - 0 ratings