如何使用Moment.js完全格式化持续时间?
鉴于UTC格式的两个日期,我想执行以下操作:
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
我尝试使用以下内容:
var duration = moment(moment(end) - moment(start)).format('hh[h] mm[m]');
但是这几天都行不通.而且,它不能用几天,因为即使< 24小时过去了,它们也总是> = 1.
But this does not work with days. Moreover, it does not work with days, since they are always >=1 even if <24 hours pass.
我也尝试过 twix.js 来获取长度,但是其格式不支持创建上面指定的格式,或者我无法在其文档中找到这样做的方法.基本上,我正在寻找twix.humanizeLength()
的精确版本.
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 的a.diff(b)
仅提供总持续时间,它可以为我提供时间间隔的长度(以分钟,小时或天为单位),但不能使用余数来计算.
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.
我的当前解决方案是使用diff
创建范围,然后使用取模来计算余数,但这不是很好:
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 ' : '');
问题:在 moment.js 或 twix.js 中,是否有更聪明的方法可以实现此目的?时间并开发我自己的moment.js插件?
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?
moment.js中有一个用于格式化持续时间的插件:矩持续时间格式
There's a plugin for formatting duration in moment.js : moment-duration-format
如果它没有满足您的要求,则应扩展moment.duration.fn
.如果您不支持许多语言环境,则应该很简单.
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.