Calculate the number of months between two dates
Count calendar month boundaries from start to end.
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
9The edge case
Input
{
"start": "2026-10-28",
"end": "2026-01-01"
}Expected output
0Know 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.
Keep exploring
- Compare two dates — Compare validated ISO calendar dates in UTC and return -1, 0 or 1.
- Add AM PM suffix to an hour — Turn an hour from 0 to 23 into a 12-hour label with am or pm.
- Calculate the number of days between two dates — Count whole calendar days between two YYYY-MM-DD dates.