Age Calculator with Validation - Problem

You need to calculate a person's age in years based on their birthdate and handle various error scenarios.

Input: A birthdate string in format "YYYY-MM-DD"

Output: Return the age as an integer, or an error message as a string

Validation Rules:

  • Invalid date format should return "Invalid date format"
  • Future dates should return "Future date not allowed"
  • Impossible dates (like February 30th) should return "Invalid date"
  • Valid dates should return the age in years

Note: Use today's date as "2024-01-15" for consistent testing.

Input & Output

Example 1 — Valid Birth Date
$ Input: birthdate = "1990-03-15"
Output: 34
💡 Note: Valid date format, not in future. Age = 2024 - 1990 = 34 (birthday has passed on March 15, 2024 > current Jan 15, 2024 is incorrect - birthday hasn't passed). Actually: 33 years old since March 15, 2024 hasn't occurred yet from Jan 15, 2024.
Example 2 — Invalid Date Format
$ Input: birthdate = "1990/03/15"
Output: "Invalid date format"
💡 Note: Wrong separator - uses '/' instead of '-', format should be YYYY-MM-DD
Example 3 — Future Date
$ Input: birthdate = "2025-01-01"
Output: "Future date not allowed"
💡 Note: Date is in the future compared to current date 2024-01-15

Constraints

  • Input is a string representing a birthdate
  • Expected format: YYYY-MM-DD
  • Current date for testing: 2024-01-15
  • Age calculated in complete years

Visualization

Tap to expand
Age Calculator with ValidationINPUTVALIDATION PROCESSRESULT"1990-03-15"Valid format example"1990/03/15"Wrong format"2025-01-01"Future date"2023-02-30"Impossible date1Format CheckYYYY-MM-DD pattern2Date ValidationCheck impossible dates3Future CheckCompare with 2024-01-154Age CalculationYear diff + birthday adjust33Valid birthdate result"Invalid date format"Format error message"Future date not allowed"Future date error"Invalid date"Impossible date errorKey Insight:Use try-catch with built-in date parsers to automatically validate formats and impossible dates,then perform simple year arithmetic with birthday adjustment for age calculation.TutorialsPoint - Age Calculator with Validation | Built-in Date Parser Approach
Asked in
Google 15 Microsoft 12 Amazon 18
25.0K 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