Difference between two dates in years, months, days in JavaScript

前端 未结 26 2465
执念已碎
执念已碎 2020-11-22 07:18

I\'ve been searching for 4 hours now, and have not found a solution to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 201

相关标签:
26条回答
  • 2020-11-22 07:53

    If you are using date-fns and if you dont want to install the Moment.js or the moment-precise-range-plugin. You can use the following date-fns function to get the same result as moment-precise-range-plugin

    intervalToDuration({
      start: new Date(),
      end: new Date("24 Jun 2020")
    })
    

    This will give output in a JSON object like below

    {
      "years": 0,
      "months": 0,
      "days": 0,
      "hours": 19,
      "minutes": 35,
      "seconds": 24
    }
    

    Live Example https://stackblitz.com/edit/react-wvxvql

    Link to Documentation https://date-fns.org/v2.14.0/docs/intervalToDuration

    0 讨论(0)
  • 2020-11-22 07:53

    With dayjs we did it in that way:

    export const getAgeDetails = (oldDate: dayjs.Dayjs, newDate: dayjs.Dayjs) => {
      const years = newDate.diff(oldDate, 'year');
      const months = newDate.diff(oldDate, 'month') - years * 12;
      const days = newDate.diff(oldDate.add(years, 'year').add(months, 'month'), 'day');
    
      return {
        years,
        months,
        days,
        allDays: newDate.diff(oldDate, 'day'),
      };
    };
    

    It calculates it perfectly including leap years and different month amount of days.

    0 讨论(0)
  • 2020-11-22 07:55

    Time span in full Days, Hours, Minutes, Seconds, Milliseconds:

    // Extension for Date
    Date.difference = function (dateFrom, dateTo) {
      var diff = { TotalMs: dateTo - dateFrom };
      diff.Days = Math.floor(diff.TotalMs / 86400000);
    
      var remHrs = diff.TotalMs % 86400000;
      var remMin = remHrs % 3600000;
      var remS   = remMin % 60000;
    
      diff.Hours        = Math.floor(remHrs / 3600000);
      diff.Minutes      = Math.floor(remMin / 60000);
      diff.Seconds      = Math.floor(remS   / 1000);
      diff.Milliseconds = Math.floor(remS % 1000);
      return diff;
    };
    
    // Usage
    var a = new Date(2014, 05, 12, 00, 5, 45, 30); //a: Thu Jun 12 2014 00:05:45 GMT+0400 
    var b = new Date(2014, 02, 12, 00, 0, 25, 0);  //b: Wed Mar 12 2014 00:00:25 GMT+0400
    var diff = Date.difference(b, a);
    /* diff: {
      Days: 92
      Hours: 0
      Minutes: 5
      Seconds: 20
      Milliseconds: 30
      TotalMs: 7949120030
    } */
    
    0 讨论(0)
  • 2020-11-22 07:55

    The following is an algorithm which gives correct but not totally precise since it does not take into account leap year. It also assumes 30 days in a month. A good usage for example is if someone lives in an address from 12/11/2010 to 11/10/2011, it can quickly tells that the person lives there for 10 months and 29 days. From 12/11/2010 to 11/12/2011 is 11 months and 1 day. For certain types of applications, that kind of precision is sufficient. This is for those types of applications because it aims for simplicity:

    var datediff = function(start, end) {
      var diff = { years: 0, months: 0, days: 0 };
      var timeDiff = end - start;
    
      if (timeDiff > 0) {
        diff.years = end.getFullYear() - start.getFullYear();
        diff.months = end.getMonth() - start.getMonth();
        diff.days = end.getDate() - start.getDate();
    
        if (diff.months < 0) {
          diff.years--;
          diff.months += 12;
        }
    
        if (diff.days < 0) {
          diff.months = Math.max(0, diff.months - 1);
          diff.days += 30;
        }
      }
    
      return diff;
    };
    

    Unit tests

    0 讨论(0)
  • 2020-11-22 07:55

    I would personally use http://www.datejs.com/, really handy. Specifically, look at the time.js file: http://code.google.com/p/datejs/source/browse/trunk/src/time.js

    0 讨论(0)
  • 2020-11-22 07:56

    Some math is in order.

    You can subtract one Date object from another in Javascript, and you'll get the difference between them in milisseconds. From this result you can extract the other parts you want (days, months etc.)

    For example:

    var a = new Date(2010, 10, 1);
    var b = new Date(2010, 9, 1);
    
    var c = a - b; // c equals 2674800000,
                   // the amount of milisseconds between September 1, 2010
                   // and August 1, 2010.
    

    Now you can get any part you want. For example, how many days have elapsed between the two dates:

    var days = (a - b) / (60 * 60 * 24 * 1000);
    // 60 * 60 * 24 * 1000 is the amount of milisseconds in a day.
    // the variable days now equals 30.958333333333332.
    

    That's almost 31 days. You can then round down for 30 days, and use whatever remained to get the amounts of hours, minutes etc.

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