(
laterDate: DateArg<Date> & {},
earlierDate: DateArg<Date> & {},
options?: DifferenceInMonthsOptions | undefined,
)
| 26 | * //=> 7 |
| 27 | */ |
| 28 | export function differenceInMonths( |
| 29 | laterDate: DateArg<Date> & {}, |
| 30 | earlierDate: DateArg<Date> & {}, |
| 31 | options?: DifferenceInMonthsOptions | undefined, |
| 32 | ): number { |
| 33 | const [laterDate_, workingLaterDate, earlierDate_] = normalizeDates( |
| 34 | options?.in, |
| 35 | laterDate, |
| 36 | laterDate, |
| 37 | earlierDate, |
| 38 | ); |
| 39 | |
| 40 | const sign = compareAsc(workingLaterDate, earlierDate_); |
| 41 | const difference = Math.abs( |
| 42 | differenceInCalendarMonths(workingLaterDate, earlierDate_), |
| 43 | ); |
| 44 | |
| 45 | if (difference < 1) return 0; |
| 46 | |
| 47 | if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27) |
| 48 | workingLaterDate.setDate(30); |
| 49 | |
| 50 | workingLaterDate.setMonth(workingLaterDate.getMonth() - sign * difference); |
| 51 | |
| 52 | let isLastMonthNotFull = compareAsc(workingLaterDate, earlierDate_) === -sign; |
| 53 | |
| 54 | if ( |
| 55 | isLastDayOfMonth(laterDate_) && |
| 56 | difference === 1 && |
| 57 | compareAsc(laterDate_, earlierDate_) === 1 |
| 58 | ) { |
| 59 | isLastMonthNotFull = false; |
| 60 | } |
| 61 | |
| 62 | const result = sign * (difference - +isLastMonthNotFull); |
| 63 | return result === 0 ? 0 : result; |
| 64 | } |
no test coverage detected