Calculate the number of months between two dates

Count calendar month boundaries from start to end.

JavaScript Version 1.0.0 · MIT · .md

calculate-the-number-of-months-between-two-dates.js
function monthDiff({ start, end }) { const a = new Date(start), b = new Date(end); return Math.max(0, (b.getUTCFullYear() - a.getUTCFullYear()) * 12 - a.getUTCMonth() + b.getUTCMonth()); }

Input & expected output

Input

{
  "start": "2026-01-15",
  "end": "2026-10-28"
}

Expected output

9

The edge case

Input

{
  "start": "2026-10-28",
  "end": "2026-01-01"
}

Expected output

0

Know the limits

  • Days are ignored: January 31 to February 1 counts as one month. An end before the start returns 0.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Calculate the number of months between two dates from the original 1loc collection by Nguyen Huu Phuoc, with kwaimind. Copyright (c) 2020 phuoc-ng. MIT licensed.

Reads validated YYYY-MM-DD dates in UTC instead of local Date objects. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.