简体   繁体   中英

Using moment.js, How can I simplify a duration to its most simplified form?

Using Moment.js to convert milliseconds to a duration :

moment.duration(dur)

and then output a string : moment.duration(dur).toISOString()

returns this : PT15336H1S

Obviously 15336 Hours is not a very useful number for a duration.

I have found a workaround to do this which is : moment.duration(moment.duration(d)._data).toISOString()

since duration._data returns a json object of this exact simplified form, passing it back into the constructor does correctly return the string I want. example :

var d = 55209601000; //milliseconds
var initialDuration = moment.duration(d)
console.log(initialDuration._data);
//{
// days:30,
// hours:0,
// milliseconds:0,
// minutes:0,
// months:8,
// seconds:1,
// years:1
//}
console.log(initialDuration.toISOString());
// "PT15336H1S"

var newDuration = moment.duration(initialDuration._data);
console.log(newDuration.toISOString());
// "P1Y8M30DT1S"

So obviously this method works, but it feels incredibly hacky. Surely there's a moment.js function or a cleaner way to do this?

This is a hole (imho) in momentjs . Even using humanize() on your duration will give a not very specific 2 years .

There is more detail in these two GitHub issues:

  1. https://github.com/moment/moment/issues/463

  2. https://github.com/moment/moment/issues/1048

It seems like the popular opinion is just to install and use this plugin:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM