Write a Python program to check whether a given date is valid date or not and to out put the following.
• If the date is valid then the message “Date is Valid” otherwise the message “Date is Invalid”.
• If the date is a valid date, then the next date.
Hint:
Follow the following steps. (NOTE: You are not allowed to use any Python built-in functions.)
• Get the inputs Year, Month, and Date separately.
• Use selection statements, i.e., if-else statements to check if the Date, Month, and the Year are valid.
• if the date is a valid date, then print the next date (Increment the date).
Sample Test Cases:
Enter the Date Expected Result Next Date
Test Case 1 2020 02 30 Date is Invalid -
Test Case 2 2020 02 29 Date is Valid 01-03-2021
Test Case 3 2021 09 31 Date is Invalid -
Test Case 4 2021 13 01 Date is Invalid -
Test Case 5 2021 08 31 Date is Valid 01-09-2021
def ch_to_int(ch):
if ch == '0':
return 0
if ch == '1':
return 1
if ch == '2':
return 2
if ch == '3':
return 3
if ch == '4':
return 4
if ch == '5':
return 5
if ch == '6':
return 6
if ch == '7':
return 7
if ch == '8':
return 8
if ch == '9':
return 9
def digit_to_str(digit):
if digit == 1:
return '01'
if digit == 2:
return '02'
if digit == 3:
return '03'
if digit == 4:
return '04'
if digit == 5:
return '05'
if digit == 6:
return '06'
if digit == 7:
return '07'
if digit == 8:
return '08'
if digit == 9:
return '09'
def is_leap_year(year):
if year % 4 == 0:
return True
if year % 4 == 0 and year % 100:
return year % 400 == 0
def check_date(year, month, day):
if year < 0:
return 'Date is Invalid'
if month < 1 or month > 12:
return 'Date is Invalid'
max_day_in_month = -1
if month in (1, 3, 5, 7, 8, 10, 12):
max_day_in_month = 31
elif month in (4, 6, 9, 11):
max_day_in_month = 30
elif month == 2:
if is_leap_year(year):
max_day_in_month = 29
else:
max_day_in_month = 28
if day < 1 or day > max_day_in_month:
return 'Date is Invalid'
day += 1
if day > max_day_in_month:
day -= max_day_in_month
month += 1
if month > 12:
month -= 12
year += 1
if month < 10:
month = digit_to_str(month)
if day < 10:
day = digit_to_str(day)
return 'Date is Valid {}-{}-{}'.format(day, month, year)
s = input()
year = 1000 * ch_to_int(s[0]) + 100 * ch_to_int(s[1]) + 10 * ch_to_int(s[2]) + ch_to_int(s[3])
month = 10 * ch_to_int(s[5]) + ch_to_int(s[6])
day = 10 * ch_to_int(s[8]) + ch_to_int(s[9])
print(check_date(year, month, day))
Comments
Leave a comment