'Calculation between months and dates (HTML - JS) [duplicate]

I am reopening this thread with more information provided.

Having February 28 days, the result is 0.933... months, not the “1 month” I expected to get in these cases of months with 28/29/31 days (see attached screenshot:

)

How can I make the difference of 2 dates automatically (even if the month has 28, 30 or 31 days) and get the result "1" instead of 0.9333?

Below is the code im using:

var date1 = new Date("02/01/2022");
var date2 = new Date("03/01/2022");

// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();

// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
// To calculate the no. of months between two dates
var Difference_In_Months = Difference_In_Time / (1000 * 3600 * 24 * 30);
console.log(Difference_In_Time);
console.log(Difference_In_Days);
console.log(Difference_In_Months);

I want to make a calculation on a field which calculates the "Minimum Duration in Month".

In cases of full months (30),the calculation is easy (end date-start date), but in cases of 31 or 28 day months, the subtraction is not very accurate.

Many thanks!

RMMA



Solution 1:[1]

const differenceInMonths = Math.abs(date1.getMonth() - date2.getMonth())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Seiteros