我需要2次返回差值
示例1:
var time1 = "1970-01-01 20:00:00";
var time2 = "1970-01-01 19:00:00";
使用momentjs代码:
var ms = moment(time2 ,"YYYY-MM-DD HH:mm:ss").diff(moment(time1 ,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
var timeOfHourExtra = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
结果还可以:"1:00:00"
但是当2个不同的天数是问题的例子:
var time1 = "1970-01-01 20:00:00"; //day1
var time2 = "1970-01-01 01:00:00"; //day2
//diference return -18:00:00
//should return 5:00:00
如何在2天不同的时间内返回正确的差异。
答案 0 :(得分:1)
您需要在获得差异之前比较日期。 Moment内置了比较日期的功能:https://momentjs.com/docs/#/displaying/difference/
您也可以跳过转换为毫秒,然后是小时。 diff
接受您想要返回的值的第二个参数。{{3}}
var time1 = "1970-01-01 20:00:00";
var time2 = "1970-01-02 01:00:00";
var timeOne = moment(time1);
var timeTwo = moment(time2);
var hourDiff = (timeOne.isBefore(timeTwo)) ?
timeTwo.diff(timeOne, "hours") :
timeOne.diff(timeTwo, "hours");
var timeOfHourExtra = hourDiff.toString() + ':00:00';
// 5:00:00