Validate a Gregorian date
Check that a year, a 1-based month and a day form a real calendar date.
function isValidDate({ year, month, day }) { const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); return day >= 1 && day <= [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]; }
Input & expected output
Input
{
"year": 2024,
"month": 2,
"day": 29
}Expected output
trueThe edge case
Input
{
"year": 2026,
"month": 2,
"day": 29
}Expected output
falseKnow the limits
- The original used a zero-based month with new Date(y, m, 0), which reads the previous month’s length and accepted February 30. This version uses a 1-based month and explicit Gregorian rules.
- The lab accepts years 1–9,999 and months 1–12.
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 Validate a Gregorian date from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Rewritten with a 1-based month and explicit Gregorian month lengths; the original zero-based month read the previous month's length and accepted February 30. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/validate-a-gregorian-date.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Check whether all values are equal — Compare every item with the first using Object.is.
- Check whether an object is empty — Check for own enumerable string keys on a JSON object.
- Check whether an integer is even — Test parity for safe integers, including zero and negative values.