Get the time difference between two datetimes

前端 未结 19 2270
花落未央
花落未央 2020-11-22 05:25

I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I\'m having a hard time trying to do something that seems simple: geting the differ

19条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 06:09

    This approach will work ONLY when the total duration is less than 24 hours:

    var now  = "04/09/2013 15:00:00";
    var then = "04/09/2013 14:20:30";
    
    moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
    
    // outputs: "00:39:30"
    

    If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.

    If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:

    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);
    var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
    
    // outputs: "48:39:30"
    

    Note that I'm using the utc time as a shortcut. You could pull out d.minutes() and d.seconds() separately, but you would also have to zeropad them.

    This is necessary because the ability to format a duration objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:

    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);
    var s = d.format("hh:mm:ss");
    
    // outputs: "48:39:30"
    

提交回复
热议问题