1 | import { normalizeDates } from "./_lib/normalizeDates.js";
|
2 | import { compareAsc } from "./compareAsc.js";
|
3 | import { differenceInCalendarMonths } from "./differenceInCalendarMonths.js";
|
4 | import { isLastDayOfMonth } from "./isLastDayOfMonth.js";
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | export function differenceInMonths(laterDate, earlierDate, options) {
|
27 | const [laterDate_, workingLaterDate, earlierDate_] = normalizeDates(
|
28 | options?.in,
|
29 | laterDate,
|
30 | laterDate,
|
31 | earlierDate,
|
32 | );
|
33 |
|
34 | const sign = compareAsc(workingLaterDate, earlierDate_);
|
35 | const difference = Math.abs(
|
36 | differenceInCalendarMonths(workingLaterDate, earlierDate_),
|
37 | );
|
38 |
|
39 | if (difference < 1) return 0;
|
40 |
|
41 | if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27)
|
42 | workingLaterDate.setDate(30);
|
43 |
|
44 | workingLaterDate.setMonth(workingLaterDate.getMonth() - sign * difference);
|
45 |
|
46 | let isLastMonthNotFull = compareAsc(workingLaterDate, earlierDate_) === -sign;
|
47 |
|
48 | if (
|
49 | isLastDayOfMonth(laterDate_) &&
|
50 | difference === 1 &&
|
51 | compareAsc(laterDate_, earlierDate_) === 1
|
52 | ) {
|
53 | isLastMonthNotFull = false;
|
54 | }
|
55 |
|
56 | const result = sign * (difference - +isLastMonthNotFull);
|
57 | return result === 0 ? 0 : result;
|
58 | }
|
59 |
|
60 |
|
61 | export default differenceInMonths;
|