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

Function differenceInYears

pkgs/core/src/differenceInYears/index.ts:30–66  ·  view source on GitHub ↗
(
  laterDate: DateArg<Date> & {},
  earlierDate: DateArg<Date> & {},
  options?: DifferenceInYearsOptions | undefined,
)

Source from the content-addressed store, hash-verified

28 * //=> 1
29 */
30export function differenceInYears(
31 laterDate: DateArg<Date> & {},
32 earlierDate: DateArg<Date> & {},
33 options?: DifferenceInYearsOptions | undefined,
34): number {
35 const [laterDate_, earlierDate_] = normalizeDates(
36 options?.in,
37 laterDate,
38 earlierDate,
39 );
40
41 // -1 if the left date is earlier than the right date
42 // 2023-12-31 - 2024-01-01 = -1
43 const sign = compareAsc(laterDate_, earlierDate_);
44
45 // First calculate the difference in calendar years
46 // 2024-01-01 - 2023-12-31 = 1 year
47 const diff = Math.abs(differenceInCalendarYears(laterDate_, earlierDate_));
48
49 // Now we need to calculate if the difference is full. To do that we set
50 // both dates to the same year and check if the both date's month and day
51 // form a full year.
52 laterDate_.setFullYear(1584);
53 earlierDate_.setFullYear(1584);
54
55 // For it to be true, when the later date is indeed later than the earlier date
56 // (2026-02-01 - 2023-12-10 = 3 years), the difference is full if
57 // the normalized later date is also later than the normalized earlier date.
58 // In our example, 1584-02-01 is earlier than 1584-12-10, so the difference
59 // is partial, hence we need to subtract 1 from the difference 3 - 1 = 2.
60 const partial = compareAsc(laterDate_, earlierDate_) === -sign;
61
62 const result = sign * (diff - +partial);
63
64 // Prevent negative zero
65 return result === 0 ? 0 : result;
66}

Callers 3

intervalToDurationFunction · 0.90
test.tsFile · 0.90
_testFunction · 0.90

Calls 3

normalizeDatesFunction · 0.90
compareAscFunction · 0.90

Tested by

no test coverage detected