使用moment.js,如何将持续时间简化为最简化的形式? [英] Using moment.js, How can I simplify a duration to its most simplified form?

查看:65
本文介绍了使用moment.js,如何将持续时间简化为最简化的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Moment.js将毫秒转换为持续时间:

Using Moment.js to convert milliseconds to a duration :

moment.duration(dur)

,然后输出一个字符串:moment.duration(dur).toISOString()

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

返回此内容:PT15336H1S

很显然,在一段时间内15336小时不是一个非常有用的数字.

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

我发现了一种解决方法,它是:moment.duration(moment.duration(d)._data).toISOString()

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

因为duration._data返回此精确简化形式的json对象, 将其传递回构造器 does 正确返回我想要的字符串. 例子:

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"

因此,显然,此方法有效,但令人难以置信.当然,有一个moment.js函数或更简洁的方法可以做到这一点?

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

推荐答案

这是momentjs中的孔(imho).即使对您的持续时间使用humanize()也会给出不太具体的2 years.

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

这两个GitHub问题中有更多详细信息:

There is more detail in these two GitHub issues:

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

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

这篇关于使用moment.js,如何将持续时间简化为最简化的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆