MCPcopy
hub / github.com/date-fns/date-fns / differenceInMonths

Function differenceInMonths

pkgs/core/src/differenceInMonths/index.ts:28–64  ·  view source on GitHub ↗
(
  laterDate: DateArg<Date> & {},
  earlierDate: DateArg<Date> & {},
  options?: DifferenceInMonthsOptions | undefined,
)

Source from the content-addressed store, hash-verified

26 * //=> 7
27 */
28export 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}

Callers 5

formatDistanceFunction · 0.90
intervalToDurationFunction · 0.90
differenceInQuartersFunction · 0.90
test.tsFile · 0.90
_testFunction · 0.90

Calls 4

normalizeDatesFunction · 0.90
compareAscFunction · 0.90
isLastDayOfMonthFunction · 0.90

Tested by

no test coverage detected