Code:
#include <stdio.h>
#define ERROR 1
#define SUCCESS 0
int ioDates(void);
int valiDate(int month, int day, int year);
int isLeapYear(int year);
int daysPassed(int month, int day, int year, int sMonth, int sDay, int sYear);
char buffer[20] = {0};
int month = 0, day = 0, year = 0;
int sMonth = 0, sDay = 0, sYear = 0;
int main()
{
ioDates();
return (0);
}
int ioDates(void) /* Gets the two dates from the user */
{
printf("\nInput first date in MM/DD/YYYY format: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d/%d/%d", &month, &day, &year);
if ((valiDate(month, day, year)) == SUCCESS)
{
printf("\nInput second date in MM/DD/YYYY format: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d/%d/%d", &sMonth, &sDay, &sYear);
}
else
ioDates();
if ((valiDate(sMonth, sDay, sYear)) == SUCCESS)
{
printf("\nThe number of days between %d/%d/%d and %d/%d/%d is %d.",
month, day, year, sMonth, sDay, sYear, daysPassed(month, day, year, sMonth, sDay, sYear));
}
else
ioDates();
return (0);
}
int valiDate(int month, int day, int year) /* Makes sure all dates are valid */
{
if (month > 0 && month < 13 && day > 0 && day < 32 && year > 0)
{
if (month == 2)
{
if(((isLeapYear(year)) == 0) && day > 29)
{
printf("\nERROR: There are only 29 days of February in %d.\n", year);
return (ERROR);
}
else if (((isLeapYear(year)) == 1) && day > 28)
{
printf("\nERROR: There are only 28 days of February in %d.\n", year);
return (ERROR);
}
}
else if ((month == 4) && (day > 30))
{
printf("\nERROR: There are only 30 days in April.\n");
return (ERROR);
}
else if ((month == 6) && (day > 30))
{
printf("\nERROR: There are only 30 days in June.\n");
return (ERROR);
}
else if ((month == 9) && (day > 30))
{
printf("\nERROR: There are only 30 days in September.\n");
return (ERROR);
}
else if ((month == 11) && (day > 30))
{
printf("\nERROR: There are only 30 days in November.\n");
return (ERROR);
}
else
{
printf("The date you typed is %d/%d/%d.\n", month, day, year);
return (SUCCESS);
}
}
else
{
printf("\nERROR: Invalid date. Please try again.\n");
return (ERROR);
}
}
int isLeapYear(int year) /* Determines if the year is a leap year */
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
{
return (SUCCESS);
}
else
{
return (ERROR);
}
}
else
{
return (SUCCESS);
}
}
else
{
return (ERROR);
}
}
int daysPassed(int month, int day, int year, int sMonth, int sDay, int sYear) /* Calculates the days between each date */
{
int diffDay = 0, diffMonth = 0, diffYear = 0;
int daysBetween = 0, daysInMonth = 31, daysInYear = 365;
diffDay = sDay - day;
diffMonth = sMonth - month;
diffYear = sYear - year;
if ((month || sMonth) == (4 || 6 || 9 || 11))
daysInMonth = 30;
if (month == 2)
{
if ((isLeapYear(year)) == SUCCESS)
{
daysInMonth = 29;
daysInYear = 366;
}
}
daysBetween = diffDay + (diffMonth * daysInMonth) + (diffYear * daysInYear);
return (daysBetween);
}