How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?
Any help would be great :)
In this case, I'm not concerned with full months, part months, how long a month is, etc. I just need to know the number of months. A relevant real world case would be where a report is due every month, and I need to know how many reports there should be.
Example:
This is an elaborated code example to show where the numbers are going.
Let's take 2 timestamps that should result in 4 months
May be slightly different with your timezone / time pulled. The day, minutes, and seconds don't matter and can be included in the timestamp, but we will disregard it with our actual calculation.
let dateRangeStartConverted = new Date(1573621200000);
let dateRangeEndConverted = new Date(1582261140000);
let startingMonth = dateRangeStartConverted.getMonth();
let startingYear = dateRangeStartConverted.getFullYear();
let endingMonth = dateRangeEndConverted.getMonth();
let endingYear = dateRangeEndConverted.getFullYear();
This gives us
(12 * (endYear - startYear)) + 1
to the ending month.2 + (12 * (2020 - 2019)) + 1 = 15
15 - 11 = 4
; we get our 4 month result.
November 2019 through March 2022 is 29 months. If you put these into an excel spreadsheet, you will see 29 rows.
3 + (12 * (2022-2019)) + 1
40 - 11 = 29