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

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

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

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

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

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

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


当前回答

 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
    }

其他回答

也许对某人有用

          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
 var start=moment(1541243900000);
 var end=moment(1541243942882);
 var duration = moment.duration(end.diff(startTime));
 var hours = duration.asHours();

如您所见,开始日期和结束日期需要是此方法工作的时刻对象。

或者你可以简单地做:

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

文档:

来源: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 " > < /脚本>

根据Moment JS的新Deprecation警告

你需要传递开始和结束日期格式的格式以及值,例如:

   let trackStartTime = "2020-12-29 09:59:19.07 +05:30";
   let trackEndTime = "2020-12-29 11:04:19.07 +05:30" || moment().format("YYYY-MM-DD HH:mm:ss.SS Z");
   let overallActivity = moment.duration(moment(trackEndTime, 'YYYY-MM-DD HH:mm:ss.SS Z').diff(moment(trackStartTime, 'YYYY-MM-DD HH:mm:ss.SS Z'))).asHours();