计算午夜后两次之间的持续时间 [英] Count duration between two times after midnight

查看:77
本文介绍了计算午夜后两次之间的持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算两次之间的持续时间?

How to count duration between two times?

var start = moment('17:00', "HH:mm");
var end = moment('02:15', "HH:mm");
moment.duration(end.diff(start)).asHours()
//outputs  -14.75 instead of 9.15

推荐答案

moment构造函数默认为当前年,月和日,因此您的问题是endstart之前.您可以使用 isBefore 比较变量,然后使用 add 到第二天转换".

moment constructor defaults to current year, month and day, so your problem is that end is before start. You can compare your variables using isBefore and then use add to "trasform" end to the next day.

请注意, asHours 给出分数值(因此, 9.25,而不是9.15).如果您需要"9小时15分钟",则可以使用 moment-duration-格式插件(例如,您可以将'h[.]m'用作 template format 方法中).

Note that asHours gives fractional values (so you'll have 9.25 instead of 9.15). If you need to get "9 hours and 15 minutes" you can use moment-duration-format plug-in (for example you caun use 'h[.]m' as template in the format method).

这里是一个工作示例:

var start = moment('17:00', "HH:mm");
var end = moment('02:15', "HH:mm");
if( end.isBefore(start) ){
  end.add(1, 'day');
}
var dur = moment.duration(end.diff(start))
var result = dur.asHours();
document.writeln(result);
document.write(dur.format('h[.]m'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.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>

这篇关于计算午夜后两次之间的持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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