我知道我可以做任何事情,还有一些更复杂的约会。但令人尴尬的是,我在尝试做一些看似简单的事情时遇到了困难:得到2倍之间的差异。

例子:

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

//expected result:
"00:39:30"

我所做的:

var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");

console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30  

我不明白这里的“10”是什么。我住在巴西,所以我们是utc-0300。

moment.duration(now.diff(then))的结果是一个具有正确内部值的持续时间:

 days: 0
 hours: 0
 milliseconds: 0
 minutes: 39
 months: 0
 seconds: 30
 years: 0

所以,我想我的问题是:如何将一个momentjs Duration转换为一个时间间隔?我肯定可以用

duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")

但我觉得有一些更优雅的东西,我完全错过了。

更新 仔细看,在上面的例子中是:

Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}

而moment(moment.duration(now.diff(then)))为:

Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}

我不确定为什么第二个值在夏令时(-0200)…但我确定我不喜欢约会:(

更新2

好吧,这个值是-0200,可能是因为31/12/1969是使用日光时间的日期……就是这样。


当前回答

这将返回最大的时间周期差异,如(4秒,2分钟,1小时,2天,3周,4个月,5年)。 我用这个来通知最近的时间。

function dateDiff(startDate, endDate) {
    let arrDate = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
    let dateMap = arrDate.map(e => moment(endDate).diff(startDate, e));
    let index = 6 - dateMap.filter(e => e == 0).length;
    return {
        type: arrDate[index] ?? "seconds",
        value: dateMap[index] ?? 0
    };
}

例子:

dateDiff("2021-06-09 01:00:00", "2021-06-09 04:01:01")

{type: "hours", value: 3}

dateDiff("2021-06-09 01:00:00", "2021-06-12 04:01:01")

{type: "days", value: 3}

dateDiff("2021-06-09 01:00:00", "2021-06-09 01:00:10")

{type: "seconds", value: 10}

其他回答

我用typescript创建了一个简单的函数

const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);

function setDiffTimeString(diffDuration: moment.Duration) {
  const str = [];
  diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
  diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
  diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
  diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
  diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
  console.log(str.join(', '));
} 
// output: 1 day(s), 23 hour(s), 29 minute(s)

生成javascript https://www.typescriptlang.org/play/index.html

如果您希望将两个时间戳的差异转换为总天数、小时和分钟,而不是月和年。

var now  = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));

Diff包含2个月23天23小时20分钟。但我们只需要在几天、几小时和几分钟内得到结果,所以简单的解决方案是:

var days = parseInt(diff.asDays()); //84

var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.

hours = hours - days*24;  // 23 hours

var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.

minutes = minutes - (days*24*60 + hours*60); //20 minutes.

最终结果是:84天23小时20分钟。

这将返回最大的时间周期差异,如(4秒,2分钟,1小时,2天,3周,4个月,5年)。 我用这个来通知最近的时间。

function dateDiff(startDate, endDate) {
    let arrDate = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
    let dateMap = arrDate.map(e => moment(endDate).diff(startDate, e));
    let index = 6 - dateMap.filter(e => e == 0).length;
    return {
        type: arrDate[index] ?? "seconds",
        value: dateMap[index] ?? 0
    };
}

例子:

dateDiff("2021-06-09 01:00:00", "2021-06-09 04:01:01")

{type: "hours", value: 3}

dateDiff("2021-06-09 01:00:00", "2021-06-12 04:01:01")

{type: "days", value: 3}

dateDiff("2021-06-09 01:00:00", "2021-06-09 01:00:10")

{type: "seconds", value: 10}

这应该可以正常工作。

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);

console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());

在ES8中使用moment, now和start是moment对象。

const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');