How to calculate date difference in JavaScript?

前端 未结 18 1754
执笔经年
执笔经年 2020-11-22 03:41

I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds. How can I do it?

相关标签:
18条回答
  • 2020-11-22 03:48

    Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:

    var difference = date2 - date1;
    

    From there, you can use simple arithmetic to derive the other values.

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

    Expressions like "difference in days" are never as simple as they seem. If you have the following dates:

    d1: 2011-10-15 23:59:00
    d1: 2011-10-16 00:01:00
    

    the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).

    Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.

    /*
       Get the number of days between two dates - not inclusive.
    
       "between" does not include the start date, so days
       between Thursday and Friday is one, Thursday to Saturday
       is two, and so on. Between Friday and the following Friday is 7.
    
       e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.
    
       If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
       use date prior to start date (i.e. 31/12/2010 to 30/1/2011).
    
       Only calculates whole days.
    
       Assumes d0 <= d1
    */
    function getDaysBetweenDates(d0, d1) {
    
      var msPerDay = 8.64e7;
    
      // Copy dates so don't mess them up
      var x0 = new Date(d0);
      var x1 = new Date(d1);
    
      // Set to noon - avoid DST errors
      x0.setHours(12,0,0);
      x1.setHours(12,0,0);
    
      // Round to remove daylight saving errors
      return Math.round( (x1 - x0) / msPerDay );
    }
    

    This can be more concise:

    /*  Return number of days between d0 and d1.
    **  Returns positive if d0 < d1, otherwise negative.
    **
    **  e.g. between 2000-02-28 and 2001-02-28 there are 366 days
    **       between 2015-12-28 and 2015-12-29 there is 1 day
    **       between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day
    **       between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days
    **        
    **  @param {Date} d0  - start date
    **  @param {Date} d1  - end date
    **  @returns {number} - whole number of days between d0 and d1
    **
    */
    function daysDifference(d0, d1) {
      var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);
      return Math.round(diff/8.64e7);
    }
    
    // Simple formatter
    function formatDate(date){
      return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-');
    }
    
    // Examples
    [[new Date(2000,1,28), new Date(2001,1,28)],  // Leap year
     [new Date(2001,1,28), new Date(2002,1,28)],  // Not leap year
     [new Date(2017,0,1),  new Date(2017,1,1)] 
    ].forEach(function(dates) {
      document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) +
                     ' is ' + daysDifference(dates[0],dates[1]) + ' days<br>');
    });

    0 讨论(0)
  • 2020-11-22 03:52
    function DateDiff(date1, date2) {
        date1.setHours(0);
        date1.setMinutes(0, 0, 0);
        date2.setHours(0);
        date2.setMinutes(0, 0, 0);
        var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference 
        return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value      
    }
    
    0 讨论(0)
  • 2020-11-22 03:53

    With momentjs it's simple:

    moment("2016-04-08").fromNow();
    
    0 讨论(0)
  • 2020-11-22 03:56

    If you are using moment.js then it is pretty simple to find date difference.

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

    Ok, there are a bunch of ways you can do that. Yes, you can use plain old JS. Just try:

    let dt1 = new Date()
    let dt2 = new Date()
    

    Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.

    dt1.setMinutes(7)
    dt2.setMinutes(42)
    console.log('Elapsed seconds:',(dt2-dt1)/1000)
    

    Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):

    var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
    var dt2 = dt1
      .plusYears(6)
      .plusMonths(12)
      .plusHours(2)
      .plusMinutes(42)
      .plusSeconds(12);
    
    // obtain the duration between the two dates
    dt1.until(dt2, ChronoUnit.YEARS); // 7
    dt1.until(dt2, ChronoUnit.MONTHS); // 84
    dt1.until(dt2, ChronoUnit.WEEKS); // 356
    dt1.until(dt2, ChronoUnit.DAYS); // 2557
    dt1.until(dt2, ChronoUnit.HOURS); // 61370
    dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
    dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
    

    There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.

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