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

前端 未结 26 2860
执念已碎
执念已碎 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:43

    How precise do you need to be? If you do need to take into account common years and leap years, and the exact difference in days between months then you'll have to write something more advanced but for a basic and rough calculation this should do the trick:

    today = new Date()
    past = new Date(2010,05,01) // remember this is equivalent to 06 01 2010
    //dates in js are counted from 0, so 05 is june
    
    function calcDate(date1,date2) {
        var diff = Math.floor(date1.getTime() - date2.getTime());
        var day = 1000 * 60 * 60 * 24;
    
        var days = Math.floor(diff/day);
        var months = Math.floor(days/31);
        var years = Math.floor(months/12);
    
        var message = date2.toDateString();
        message += " was "
        message += days + " days " 
        message += months + " months "
        message += years + " years ago \n"
    
        return message
        }
    
    
    a = calcDate(today,past)
    console.log(a) // returns Tue Jun 01 2010 was 1143 days 36 months 3 years ago
    

    Keep in mind that this is imprecise, in order to calculate the date with full precision one would have to have a calendar and know if a year is a leap year or not, also the way I'm calculating the number of months is only approximate.

    But you can improve it easily.

提交回复
热议问题