Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

monthsBetween

Returns the number of full months between two dates. Ignores time and day parts — only year and month are considered.

TypeScript
Copied!
1/**
2 * Returns the number of full months between two dates.
3 * Ignores time and day parts—only year and month are considered.
4 *
5 * @param date1 - First date.
6 * @param date2 - Second date.
7 * @returns Number of full months between the two dates.
8 */
9export function monthsBetween(date1: Date, date2: Date): number {
10  const year1 = date1.getFullYear();
11  const month1 = date1.getMonth();
12
13  const year2 = date2.getFullYear();
14  const month2 = date2.getMonth();
15
16  return Math.abs((year2 - year1) * 12 + (month2 - month1));
17}
  • Ignores Time and Day Components

    Only considers year and month, ensuring consistency across date comparisons regardless of day or time.

  • Handles Negative Ranges Gracefully

    Uses Math.abs, so it supports reversed inputs without requiring manual sorting or prevalidation.

  • Lightweight and Efficient

    Avoids use of any external libraries or heavy date operations - just pure arithmetic on native Date objects.

  • Clear and Deterministic Logic

    Simple formula based on calendar month math - no reliance on locale or timezone nuances.

Tests | Examples

TypeScript
Copied!
1test('monthsBetween - same month returns 0', () => {
2  const d1 = new Date('2023-05-10');
3  const d2 = new Date('2023-05-25');
4  expect(monthsBetween(d1, d2)).toBe(0);
5});
6
7test('monthsBetween - one month apart', () => {
8  const d1 = new Date('2023-04-30');
9  const d2 = new Date('2023-05-01');
10  expect(monthsBetween(d1, d2)).toBe(1);
11});
12
13test('monthsBetween - several months apart', () => {
14  const d1 = new Date('2022-01-01');
15  const d2 = new Date('2023-04-01');
16  expect(monthsBetween(d1, d2)).toBe(15);
17});
18
19test('monthsBetween - handles reversed dates', () => {
20  const d1 = new Date('2023-08-15');
21  const d2 = new Date('2022-08-15');
22  expect(monthsBetween(d1, d2)).toBe(12);
23});

Common Use Cases

  • Subscription Billing Calculations

    Determine how many full months a user has been subscribed or should be charged for.

  • Employee Tenure Tracking

    Calculate how many months someone has been employed based on start and end dates.

  • Loan or Lease Duration Analysis

    Measure the number of monthly intervals between loan issuance and payoff dates.

  • Data Grouping or Bucketing

    Group or segment records by the number of full months elapsed between two events.

  • Generating Monthly Reports or Stats

    Useful for defining report intervals or calculating how many months of data should be aggregated.

Codebase: Utilities -> Dates -> monthsBetween | Yevhen Klymentiev