我必须计算剩余日期和小时数的两个日期的持续时间。
如果两个日期的日期不同,则需要以天和小时为单位返回持续时间。
例如,给出以下输入:
2016-12-11T09:30:00.000Z
和2016-12-12T11:30:00.000Z
我想要这样的输出:
1天2小时
如何使用moment.js实现这一目标?
您可以使用矩量持续时间格式的插件。
只需从您的字符串/日期创建一刹那对象,然后使用diff
方法获得毫秒数差即可创建一个持续时间对象。根据需要使用format
从矩持续时间格式到打印持续时间的方法。
这是一个工作示例:
// Create moment objects
var m1 = moment('2016-12-11T09:30:00.000Z');
var m2 = moment('2016-12-12T11:30:00.000Z');
// Get the difference in milliseconds
var diff = Math.abs( m1.diff(m2) );
// Format duration according your needs
console.log(moment.duration(diff).format("d [day] h [hrs]"));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句