1 | import { toDate } from "./toDate.mjs";
|
2 |
|
3 | /**
|
4 | * @name differenceInCalendarMonths
|
5 | * @category Month Helpers
|
6 | * @summary Get the number of calendar months between the given dates.
|
7 | *
|
8 | * @description
|
9 | * Get the number of calendar months between the given dates.
|
10 | *
|
11 | * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
|
12 | *
|
13 | * @param dateLeft - The later date
|
14 | * @param dateRight - The earlier date
|
15 | *
|
16 | * @returns The number of calendar months
|
17 | *
|
18 | * @example
|
19 | * // How many calendar months are between 31 January 2014 and 1 September 2014?
|
20 | * const result = differenceInCalendarMonths(
|
21 | * new Date(2014, 8, 1),
|
22 | * new Date(2014, 0, 31)
|
23 | * )
|
24 | * //=> 8
|
25 | */
|
26 | export function differenceInCalendarMonths(dateLeft, dateRight) {
|
27 | const _dateLeft = toDate(dateLeft);
|
28 | const _dateRight = toDate(dateRight);
|
29 |
|
30 | const yearDiff = _dateLeft.getFullYear() - _dateRight.getFullYear();
|
31 | const monthDiff = _dateLeft.getMonth() - _dateRight.getMonth();
|
32 |
|
33 | return yearDiff * 12 + monthDiff;
|
34 | }
|
35 |
|
36 | // Fallback for modularized imports:
|
37 | export default differenceInCalendarMonths;
|