Validate Date Function - Problem

Create a function that validates whether a given date is valid or not. The function should take three parameters: day, month, and year.

Your function must handle:

  • Leap years: A year is a leap year if it's divisible by 4, except for years divisible by 100 (unless also divisible by 400)
  • Month-specific day limits: Different months have different numbers of days (28/29, 30, or 31)
  • Invalid ranges: Month must be 1-12, day must be positive and within the month's limit

Return true if the date is valid, false otherwise.

Input & Output

Example 1 — Valid Leap Year Date
$ Input: day = 29, month = 2, year = 2024
Output: true
💡 Note: 2024 is a leap year (divisible by 4), so February has 29 days. Day 29 is valid.
Example 2 — Invalid Non-Leap Year
$ Input: day = 29, month = 2, year = 2023
Output: false
💡 Note: 2023 is not a leap year, so February only has 28 days. Day 29 is invalid.
Example 3 — Invalid Month
$ Input: day = 15, month = 13, year = 2024
Output: false
💡 Note: Month 13 is invalid (must be 1-12), so the date is invalid regardless of day.

Constraints

  • 1 ≤ day ≤ 31
  • 1 ≤ month ≤ 12
  • 1 ≤ year ≤ 9999

Visualization

Tap to expand
INPUTVALIDATIONRESULTDay29Month2Year2024February 29, 2024Need to validate this date1Check Month Range2 ∈ [1,12] ✓2Check Leap Year2024%4==0 → true3Get Max DaysFeb leap → 29 days4Validate Day29 ≤ 29 ✓trueValid DateFebruary 29, 2024exists in leap yearAll validation rules passedMonth valid, leap year, day in rangeKey Insight:Use leap year formula (year%4==0 and (year%100!=0 or year%400==0)) plus month-day lookup for instant validationTutorialsPoint - Validate Date Function | Optimized Array Lookup
Asked in
Google 25 Amazon 18 Microsoft 15
30.3K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen