In this tutorial, we will write a C program to check date is valid or not. Given the date, month and year, the program finds whether it is valid or not. Although before jumping to the main program, you should have knowledge of the following topics in C programming.
The valid Range for a date, month, and year is 1/1/1800 – 31/12/9999.
Explanation- What does the following program check for:
- For Date: The date cannot be less than 1 and more than 31.
- For Month: Month cannot be less than 1 and more than 12
- For year: The maximum and minimum year is taken before the main program that is less than 1800 and more than 9999.
- Leap Year: Checks if the year is a leap year or not.
- If it is a leap year, the February month will have 29 days.
- If it is not a leap year, the February month will have 28 days.
- For 30 days month: The months April, June, September, and November cannot have more than 30 days
C Program Date is Valid or Not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #include <stdio.h> //take constant value for min and max year #define max_yr 9999 #define min_yr 1800 /*function to check the leap year if yes returns 1 else 0*/ int isleapYear(int y) { if ((y % 4 == 0) && (y % 100 != 0) && (y % 400 == 0)) return 1; else return 0; } //separate function to valid date or not int isDateValid(int d, int m, int y) { if (y < min_yr || y > max_yr) return 0; if (m < 1 || m > 12) return 0; if (d < 1 || d > 31) return 0; /*for february month if leap year feb has 29 days else 28 days*/ if (m == 2) { if (isleapYear(y)) { if (d <= 29) return 1; else return 0; } } //for 30 days months (April, June, September and November) if (m == 4 || m == 6 || m == 9 || m == 11) if (d <= 30) return 1; else return 0; return 1; } //main function int main(int argc, char const *argv[]) { int d, m, y; printf("Enter date (DD/MM/YYYY format): "); scanf("%d/%d/%d", &d, &m, &y); if (isDateValid(d, m, y)) printf("Date is valid."); else printf("Date is not valid."); return 0; } |
Output:
Enter date (DD/MM/YYYY format): 13/06/1998
Date is valid.