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

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

    I've stumbled upon this while having the same problem. Here is my code. It totally relies on the JS date function, so leap years are handled, and does not compare days based on hours, so it avoids daylight saving issues.

    function dateDiff(start, end) {
        let years = 0, months = 0, days = 0;
        // Day diffence. Trick is to use setDate(0) to get the amount of days
        // from the previous month if the end day less than the start day.
        if (end.getDate() < start.getDate()) {
            months = -1;
            let datePtr = new Date(end);
            datePtr.setDate(0);
            days = end.getDate() + (datePtr.getDate() - start.getDate());
        } else {
            days = end.getDate() - start.getDate();
        }
    
        if (end.getMonth() < start.getMonth() ||
           (end.getMonth() === start.getMonth() && end.getDate() < start.getDate())) {
            years = -1;
            months += end.getMonth() + (12 - start.getMonth());
        } else {
            months += end.getMonth() - start.getMonth();
        }
    
        years += end.getFullYear() - start.getFullYear();
        console.log(`${years}y ${months}m ${days}d`);
        return [years, months, days];
    }
    

提交回复
热议问题