Calculate the number of days between two dates
Count whole calendar days between two YYYY-MM-DD dates.
function diffDays({ first, second }) { return Math.round(Math.abs(Date.parse(second) - Date.parse(first)) / 86400000); }
Input & expected output
Input
{
"first": "2014-12-19",
"second": "2020-01-01"
}Expected output
1839The edge case
Input
{
"first": "2026-10-28",
"second": "2026-10-28"
}Expected output
0Know the limits
- Both dates are UTC calendar days, so daylight-saving changes cannot add or lose an hour. The original rounded local Date differences up with Math.ceil.
- The result is absolute: the order of the dates does not change it.
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 difference days between two dates from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses validated UTC calendar dates and Math.round instead of Math.ceil on local Date objects, avoiding daylight-saving errors. 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.
- Convert a date to YYYY-MM-DD format — Format an ISO date-time as its UTC calendar date.