C Program to Check if date is valid or not

In this article, we are going to learn C Program to check if date is valid or not provided by the user. We will validate the year, month, and day to confirm the date is valid. Also, we will cover the leap year special cases where February has 29 days instead of the normal 28 days. so let us begin.

C program to validate date


  • First we will check the year is with in a range of 1200 to 2900. If year is with this range then we will accept it as a valid year and move to month section.If the year is not within this range then we will notify user that year is invalid.
  • Next we will check the Month is with in a range of 1(Jan) to 12 (December). If month is with this range then we will accept it as a valid month and move to day section.
    If the month is not within this range then we will notify user that month is invalid.
  • Next we will check the day is with in a range of 1 to 30 or 1 to 31 or special cases for feb leap year. If day is with this range then we will accept it as a valid day.If the day is not within this range then we will notify user that day is invalid.
  • Once all checks pass we will accept this as a Valid date.

#include <stdio.h>
int main()
{
	int day,month,year;
	
	printf("Enter date (DD/MM/YYYY format): ");
	scanf("%d/%d/%d",&day,&month,&year);
	
	

	if(year>=1200 && year<= 2900)
	{
		
		if(month>=1 && month<=12)
		{
			
			if((day >= 1 && day <= 31) && (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12))
			{
				printf("The Date you entered is valid.\n");
			}
			else if((day>=1 && day<=30) && (month==4 || month==6 || month==9 || month==11))
			{
				printf("The Date you entered is valid.\n");
			}
			else if((day>=1 && day<=28) && (month==2))
			{
				printf("The Date you entered is valid.\n");
			}
			else if(day==29 && month==2 && (year%400==0 ||(year%4==0 && year%100!=0)))
			{
				printf("The Date you entered is valid.\n");
			}
			else
				printf("The Day you entered is invalid.\n");
		}
		else
		{
			printf("The Month you entered is not valid.\n");
		}
	}
	else
	{
		printf("The Year you entered is not Valid.\n");
	}
	
	return 0;    
}

Output

Enter date (DD/MM/YYYY format): 12/12/1213
The Date you entered is valid.

Enter date (DD/MM/YYYY format): 56/12/2012
The Day you entered is invalid.

Enter date (DD/MM/YYYY format): 12/17/2020
The Month you entered is not valid.