Get the time difference between two datetimes

前端 未结 19 1965
花落未央
花落未央 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.

    0 讨论(0)
  • 2020-11-22 06:03

    DATE TIME BASED INPUT

        var dt1 = new Date("2019-1-8 11:19:16");
        var dt2 = new Date("2019-1-8 11:24:16");
    
    
        var diff =(dt2.getTime() - dt1.getTime()) ;
        var hours = Math.floor(diff / (1000 * 60 * 60));
        diff -= hours * (1000 * 60 * 60);
        var mins = Math.floor(diff / (1000 * 60));
        diff -= mins * (1000 * 60);
    
    
        var response = {
            status : 200,
            Hour : hours,
            Mins : mins
        }
    

    OUTPUT

    {
    "status": 200,
    "Hour": 0,
    "Mins": 5
    }
    
    0 讨论(0)
  • 2020-11-22 06:04

    If you want a localized number of days between two dates (startDate, endDate):

    var currentLocaleData = moment.localeData("en");
    var duration = moment.duration(endDate.diff(startDate));
    var nbDays = Math.floor(duration.asDays()); // complete days
    var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);
    

    nbDaysStr will contain something like '3 days';

    See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.

    0 讨论(0)
  • 2020-11-22 06:08

    Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.

    It doesn't give you exactly the format you're looking for, but

    moment.duration(now.diff(then)).humanize()

    would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be

    [diff.asHours(), diff.minutes(), diff.seconds()].join(':')

    where var diff = moment.duration(now.diff(then)). This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-11-22 06:09

    I create a simple function with 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)
    

    for generate javascript https://www.typescriptlang.org/play/index.html

    0 讨论(0)
提交回复
热议问题