...

/

Solution Review: Compare Two Given Dates

Solution Review: Compare Two Given Dates

Follow the step-by-step instructions to compare two given dates.

Solution

RUN the code given below and see the output!

Press + to interact
# include <stdio.h>
struct date
{
int day, month, year ;
} ;
int checkDate ( struct date *dt );
int compareDates ( struct date d1, struct date d2 );
int main( )
{
int flag1, flag2, flag3 ;
struct date d1 = {21, 3, 2019};
struct date d2 = {21, 3, 2019};
flag1 = checkDate ( &d1 ) ;
flag2 = checkDate( &d2 ) ;
if ( flag1 == 1 || flag2 == 1 )
printf ( "Invalid date\n" ) ;
int flag ;
flag = compareDates( d1, d2 ) ;
printf ( "flag = %d", flag ) ;
return 0 ;
}
// Check if the format of date is valid or not
int checkDate ( struct date *dt )
{
// Check if date is invalid
if ( ( dt -> day > 31 || dt -> day < 0 ) ||
( dt -> month > 12 || dt -> month < 0 ) ||
( dt -> year > 9999 || dt -> year < 1000 ) )
// If date is invalid return -1
return ( -1 ) ;
else
// If date is valid return 0
return ( 0 ) ;
}
// Check if the dates are equal or not
int compareDates ( struct date d1, struct date d2 )
{
// Declare varaibles of type int
int flag1, flag2;
// Check if the d1 is in valid format
flag1 = checkDate ( &d1 ) ;
// Check if the d2 is in valid format
flag2 = checkDate( &d2 ) ;
// If one of the date is invalid then return -1
if ( flag1 == -1 || flag2 == -1 ){
return -1;
}
// Check if dates are equal
if ( ( d1.day == d2.day ) && ( d1.month == d2.month ) &&
( d1.year == d2.year ) )
// If dates are equal then return 0
return 0 ;
else
// If dates are not equal then return 1
return 1 ;
}

Explanation

struct date

We have defined the structure, date, on lines 3-6. ...