Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to check if a date is valid or not
In C programming, validating a date requires checking multiple constraints including day, month, year ranges, leap years, and month-specific day limits. A valid date should range from 1/1/1800 to 31/12/9999.
Syntax
int datevalid(int day, int month, int year); int isleap(int year);
Date Validation Constraints
- Date must be between 1 and 31
- Month must be between 1 and 12
- Year must be between 1800 and 9999
- April, June, September, November have maximum 30 days
- February has 29 days in leap years, 28 days otherwise
Example: Complete Date Validation
This program implements comprehensive date validation with leap year checking −
#include <stdio.h>
#define MAX_YEAR 9999
#define MIN_YEAR 1800
// Function to check if year is leap year
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return 1;
else
return 0;
}
// Function to validate date
int isValidDate(int day, int month, int year) {
// Check year range
if (year < MIN_YEAR || year > MAX_YEAR)
return 0;
// Check month range
if (month < 1 || month > 12)
return 0;
// Check day range
if (day < 1 || day > 31)
return 0;
// Check February
if (month == 2) {
if (isLeapYear(year)) {
return (day <= 29);
} else {
return (day <= 28);
}
}
// Check months with 30 days
if (month == 4 || month == 6 || month == 9 || month == 11) {
return (day <= 30);
}
// All other months have 31 days
return 1;
}
int main() {
int day1 = 29, month1 = 11, year1 = 2002;
int day2 = 29, month2 = 2, year2 = 2001;
int day3 = 29, month3 = 2, year3 = 2004;
printf("Date %d/%d/%d: ", day1, month1, year1);
if (isValidDate(day1, month1, year1))
printf("Valid<br>");
else
printf("Invalid<br>");
printf("Date %d/%d/%d: ", day2, month2, year2);
if (isValidDate(day2, month2, year2))
printf("Valid<br>");
else
printf("Invalid<br>");
printf("Date %d/%d/%d: ", day3, month3, year3);
if (isValidDate(day3, month3, year3))
printf("Valid<br>");
else
printf("Invalid<br>");
return 0;
}
Date 29/11/2002: Valid Date 29/2/2001: Invalid Date 29/2/2004: Valid
How It Works
- Leap Year Logic: A year is leap if divisible by 4 but not by 100, or divisible by 400
- Month Validation: Checks 30-day months (April, June, September, November) separately
- February Validation: Uses leap year check to determine maximum days (28 or 29)
- Range Validation: Ensures year is between 1800-9999
Conclusion
Date validation in C requires systematic checking of year range, month limits, and day constraints based on calendar rules. The leap year calculation is crucial for February validation.
Advertisements
