Valid Calendar Date
Return True if s is a valid calendar date written as YYYY-MM-DD, otherwise False. All of these must hold:
shas exactly 10 characters: four digits, a-, two digits, a-, two digits.- The year
YYYYis0001to9999(so0000is not valid). - The month
MMis01to12. - The day
DDis01up to the number of days in that month: 31 for January, March, May, July, August, October and December; 30 for April, June, September and November; 28 for February, or 29 when the year is a leap year. - A year is a leap year when it is divisible by 4, except that a year divisible by 100 is a leap year only when it is also divisible by 400.
Anything else, such as letters, extra characters or a missing zero as in 2024-5-01, makes the date invalid.
Example 1
s "2024-02-29"
returns true
2024 is divisible by 4 and not by 100, so February has 29 days.
Example 2
s "2023-02-29"
returns false
2023 is not a leap year, so February 29 does not exist.
Example 3
s "2024-5-01"
returns false
The month must be written with two digits.
Constraints
0 <= len(s) <= 12shas digits, letters, spaces,-and/only
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Strings problems
- Valid UsernameEasy
- Well-Formed SumEasy
- Add the FractionsMedium
- Count and SayMedium
- Expand Character RangesMedium
- Falling DominoesMedium
- Fit the Capital PatternMedium
- Kth Letter of the Unpacked TextMedium