How to calculate the difference between two dates?

cylam1000 used Ask the Experts™
How to calculate the difference between two dates?
I forgot the leap year problem, how can I improve the following program?

# include <stdio.h>
# include <math.h>

int main(void)
int InputY[2], InputM[2], InputD[2], no_of_month, days_of_month, cnt, cnt2, x;
double sum[2];
int month_day[12]={31,28,31,30,31,30,31,31,30,31,30,31};

printf ("\nPlease input the first date:\n\n");
printf ("Year in yyyy form:");
scanf ("%d",&InputY[0]);
printf ("Month in mm form:");
scanf ("%d",&InputM[0]);
printf ("Day in dd form:");
scanf ("%d",&InputD[0]);

printf ("\n\nPlease input the second date:\n");
printf ("Year in yyyy form:");
scanf ("%d",&InputY[1]);
printf ("Month in mm form:");
scanf ("%d",&InputM[1]);
printf ("Day in dd form:");
scanf ("%d",&InputD[1]);

/* calculate the difference between the two input date and the date 1/1/1753 respectively*/
for (x=0; x<=1; x++)

for (cnt=1; cnt<=no_of_month; cnt++)

sum[x]=((InputY[x]-1753)*365 + days_of_month + InputD[x]);

printf ("\nThe difference between two date = %.0f\n", fabs(sum[0]-sum[1]));
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2014
Top Expert 2015
int jdn(int day,int month,int year){
   if( month < 3 ){ month += 12; year -= 1; }
   return 1721088+day+(month-2)*367/12+year*365+year/4-year/100+year/400;
printf("\nThe difference between two date = %d",

Um, difftime()?

Convert to Julian date and just subtract. (I think that is what jdn() is intended to do.) Alternatively, convert to time_t, subtract, and divide by 24 * 3600. (OK, that ignores leap seconds...)

As far as improvements, you might want to split out the date input routine...that would save code, and make it easier to validate the input (right now the user could specify the 5000th month or day...). It would also be nice to create a type for dates, or better still, use an existing one. Keeping multiple arrays each with one component of both dates does not lend itself to later intelligibility or code reuse.
Top Expert 2006

No comment has been added lately and this question is therefore classified abandoned.

If asker wishes to close the question, then refer to

Otherwise, I will leave a recommendation in the Cleanup topic area that this question is:
PAQed with A grade to ozo  

PS: ozo, your posts are really hard to read in absence of any explanation

Please leave any comments here within the next seven days. It is assumed that any participant not responding to this request is no longer interested in its final disposition.


EE Cleanup Volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial