Skip to content Skip to sidebar Skip to footer

How To Calculate Years And Months Between Two Dates In Javascript?

Is there a way to calculate the count of years (considering leap years also) and months between two different dates in Javascript?

Solution 1:

Here is the best way I know to get years and months:

// Assumes Date From (df) and Date To (dt) are valid etc...var df= newDate("01/15/2010");
var dt = newDate("02/01/2012");   
var allMonths= dt.getMonth() - df.getMonth() + (12 * (dt.getFullYear() - df.getFullYear()));
var allYears= dt.getFullYear() - df.getFullYear();
var partialMonths = dt.getMonth() - df.getMonth();
if (partialMonths < 0) {
    allYears--;
    partialMonths = partialMonths + 12;
}
var total = allYears + " years and " + partialMonths + " months between the dates.";
var totalMonths = "A total of " + allMonths + " between the dates.";
console.log(total);
console.log(totalMonths);  


return {jaren: allYears, maanden: partialMonths};

Solution 2:

Solution 3:

You will find a complete javascript function here with validation.

Edit: Link is dead - here is a simple JS line that calculates the difference in months between two dates:

return dateTo.getMonth() - dateFrom.getMonth() + 
       (12 * (dateTo.getFullYear() - dateFrom.getFullYear()));

That is assuming that you have the dates in two variables called dateTo and dateFrom.

Solution 4:

Have a look at the JavaScript Date object.

Post a Comment for "How To Calculate Years And Months Between Two Dates In Javascript?"