C program to validate date (Check date is valid or not)

This program will read date from user and validate whether entered date is correct or not with checking of leap year. The logic behind to implement this program,

  • Enter date.
  • Check year validation, if year is not valid print error.
  • If year is valid, check month validation (i.e. month is between 1 to 12), if month is not valid print error.
  • If month is valid, then finally check day validation with leap year condition, here we will day range from 1 to 30, 1 to 31, 1 to 28 and 1 to 29.
  • If day is valid print date is correct otherwise print error.

Validating/Checking Date using C program

/*C program to validate date (Check date is valid or not).*/
 
#include <stdio.h>
 
int main()
{
    int dd,mm,yy;
     
    printf("Enter date (DD/MM/YYYY format): ");
    scanf("%d/%d/%d",&dd,&mm,&yy);
     
    //check year
    if(yy>=1900 && yy<=9999)
    {
        //check month
        if(mm>=1 && mm<=12)
        {
            //check days
            if((dd>=1 && dd<=31) && (mm==1 || mm==3 || mm==5 || mm==7 || mm==8 || mm==10 || mm==12))
                printf("Date is valid.\n");
            else if((dd>=1 && dd<=30) && (mm==4 || mm==6 || mm==9 || mm==11))
                printf("Date is valid.\n");
            else if((dd>=1 && dd<=28) && (mm==2))
                printf("Date is valid.\n");
            else if(dd==29 && mm==2 && (yy%400==0 ||(yy%4==0 && yy%100!=0)))
                printf("Date is valid.\n");
            else
                printf("Day is invalid.\n");
        }
        else
        {
            printf("Month is not valid.\n");
        }
    }
    else
    {
        printf("Year is not valid.\n");
    }
 
    return 0;    
}

Output

First Run:
Enter date (DD/MM/YYYY format): 17/03/1998
Date is valid.

Second Run:
Enter date (DD/MM/YYYY format): 29/02/2013
Day is invalid.

C Advance Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.