计算日期持续时间

时间:2016-08-24 13:51:11

标签: momentjs

我必须计算剩余天数和小时数的两个日期的持续时间。

如果两个日期有不同的日期,我需要以天和小时的形式返回持续时间。

例如,给出以下输入:

  

2016-12-11T09:30:00.000Z2016-12-12T11:30:00.000Z

我想有这个输出:

  

1天2小时

如何使用moment.js实现这一目标?

1 个答案:

答案 0 :(得分:2)

您可以使用moment-duration-format插件。

只需从字符串/日期创建时刻对象,然后使用diff方法获得以毫秒为单位的差异,以便创建duration对象。使用moment-duration-format中的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>
&#13;
&#13;
&#13;