我可以使用MomentJs得到两个日期之间的差异,如下所示:

moment(end.diff(startTime)).format("m[m] s[s]")

但是,我还想在适用的情况下显示小时(仅当>= 60分钟已经过时)。

然而,当我试图检索持续时间小时使用以下:

var duration = moment.duration(end.diff(startTime));
var hours = duration.hours();

它返回当前的小时数,而不是两个日期之间的小时数。

我如何得到两个时刻之间的小时差?


当前回答

下面的代码块展示了如何使用MomentJS计算两个日期之间的天数差异。

var now = moment(new Date()); //todays date
var end = moment("2015-12-1"); // another date
var duration = moment.duration(now.diff(end));
var days = duration.asDays();
console.log(days)

其他回答

或者你可以简单地做:

var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');

console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4

文档:

也许对某人有用

          var ax = moment(
            new Date().toLocaleString(), // today/now is 09/12/2021 10:00:00
            "DD/MM/YYYY HH:mm:ss"
            ).diff(
              moment(
                "12/11/2022 13:43:11", // some time in future or past
                "DD/MM/YYYY HH:mm:ss"
              )
          );
          console.log('if today is in the future of the compared date then 
          result should be negative ==>', ax);
          // ax bigger than 0 zero means date in past. ms less than zero is in future
 calcDifferential(from, to) {
      const fromTime = this.$moment(from, 'hh:mm:ss')
      const toTime = this.$moment(to, 'hh:mm:ss')
      const ms = toTime.diff(fromTime)
      const d = this.$moment.duration(ms)
      const s = d.format()
      return s
    }

我知道这很老了,但这里有一个简单的解决方案:

const hourDiff = start.diff(end, "hours");

开始和结束都是力矩对象。

享受吧!

来源:https://momentjs.com/docs/ / /显示/不同

let startDate = "2022-08-14"; let endDate = "2022-08-20"; let startDateMoment = moment(startDate.split('-'));// ["2022", "08", "14"] let endDateMoment = moment(endDate.split('-')); console.log('Difference: ', endDateMoment. log)diff (startDateMoment '时间'));/ / 6 < script src = " https://momentjs.com/downloads/moment.js " > < /脚本>