Home > Web Front-end > JS Tutorial > How do you calculate the difference in months between two dates in JavaScript?

How do you calculate the difference in months between two dates in JavaScript?

DDD
Release: 2024-11-12 07:32:02
Original
609 people have browsed it

How do you calculate the difference in months between two dates in JavaScript?

Calculating Months Difference between Dates in JavaScript

In JavaScript, determining the difference between two Date() objects can be a straightforward process. However, extracting only the number of months from this difference requires careful consideration, as there are multiple interpretations of what constitutes this value.

To cater to different scenarios, a JavaScript function can be created that calculates the month difference based on specific criteria. One possible approach involves obtaining the year, month, and day of month from both dates and using these values to compute the number of months. For example:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}
Copy after login

This function adds the difference in months from the years to the difference in months from the individual dates, adjusting for negative values to ensure a non-negative result.

Using this function, month differences can be calculated and displayed as follows:

function test(d1, d2) {
    var diff = monthDiff(d1, d2);
    console.log(
        d1.toISOString().substring(0, 10),
        "to",
        d2.toISOString().substring(0, 10),
        ":",
        diff
    );
}

test(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 16

test(
    new Date(2010, 0, 1),  // January 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 2

test(
    new Date(2010, 1, 1),  // February 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 1
Copy after login

In these test cases, the function correctly calculates the month differences between the specified date ranges.

The above is the detailed content of How do you calculate the difference in months between two dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template