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

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

    I have created, yet another one, function for this purpose:

    function dateDiff(date) {
        date = date.split('-');
        var today = new Date();
        var year = today.getFullYear();
        var month = today.getMonth() + 1;
        var day = today.getDate();
        var yy = parseInt(date[0]);
        var mm = parseInt(date[1]);
        var dd = parseInt(date[2]);
        var years, months, days;
        // months
        months = month - mm;
        if (day < dd) {
            months = months - 1;
        }
        // years
        years = year - yy;
        if (month * 100 + day < mm * 100 + dd) {
            years = years - 1;
            months = months + 12;
        }
        // days
        days = Math.floor((today.getTime() - (new Date(yy + years, mm + months - 1, dd)).getTime()) / (24 * 60 * 60 * 1000));
        //
        return {years: years, months: months, days: days};
    }
    

    Doesn't require any 3rd party libraries. Takes one argument -- date in YYYY-MM-DD format.

    https://gist.github.com/lemmon/d27c2d4a783b1cf72d1d1cc243458d56

提交回复
热议问题