Get the time difference between two datetimes

前端 未结 19 2268
花落未央
花落未央 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:03

    If you want difference of two timestamp into total days,hours and minutes only, not in months and years .

    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 contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:

    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.
    

    Final result will be : 84 days, 23 hours, 20 minutes.

提交回复
热议问题