Gregorian dates in JavaScript
A reliable calendar grid begins with a clear distinction: a civil date is a year, month, and day; an instant is a point on a timeline.
The Gregorian leap-year rule
A year is a leap year when it is divisible by four, except century years must also be divisible by 400. Thus 1900 is not a leap year, 2000 is, and February 2028 has 29 days. This rule keeps the Gregorian year aligned with the solar year over long spans.
function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }Model dates as civil fields
Calendar Lab represents dates with { year, month, day }, using a zero-based month internally. It validates each field before calculating. Month lengths follow the leap-year rule; weekdays are obtained from a UTC date built from those civil fields.
UTC is used here as a neutral arithmetic scale, not as a claim that a user’s date occurs at midnight UTC. A civil date remains the same label in every time zone. Using local instants and subtracting 24-hour durations can cross daylight-saving transitions with 23- or 25-hour days; converting such durations back to a date grid can therefore introduce errors.
Build the visible month
For a Monday-first grid, calculate the first date’s weekday and rotate it to a leading-cell count. Add that number of days before the month’s first date, then continue in seven-day rows until the month is complete. A fixed six-week layout always produces 42 cells; a minimal layout uses the fewest complete rows.
Adjacent dates should still be generated when hidden. Leave their cells blank instead of removing them so columns remain aligned. The Calendar Explorer demonstrates both display choices.
Validate boundaries, not just common months
Useful checks include January 1, 2027 (Friday), January 1, 2028 (Saturday), February 29, 2028 (Tuesday), and century leap rules for 1900 and 2000. These cover weekday rotation, leap-day inclusion, and exceptional years. Automated tests in the source archive exercise those boundaries and ISO year transitions.
Try the date difference calculator or the ISO week visualizer to use the same engine in a browser.