#include <time.h>
#define SECONDS_PER_DAY (24 * 60 * 60)
time_t time_from_date(int year, unsigned month, unsigned day)
{
return mktime(&(struct tm){
.tm_year = year - 1900, .tm_mon = month - 1, .tm_mday = day });
}
int days_between(int year0, unsigned month0, unsigned day0,
int year1, unsigned month1, unsigned day1)
{
return difftime(time_from_date(year1, month1, day1),
time_from_date(year0, month0, day0)) / SECONDS_PER_DAY;
}
You don't need nested conditionals at all for this.
Hint: instead of trying to determine whether a given year is a leap year, try to determine the total number of leap days that came before it.
Leap year algorithm from wikipedia:
Pseudocode 1:
if year modulo 400 is 0 then leap
else if year modulo 100 is 0 then no_leap
else if year modulo 4 is 0 then leap
else no_leap
Pseudocode 2:
function isLeapYear (year):
if ((year modulo 4 is 0) and (year modulo 100 is not 0)) or (year modulo 400 is 0)
then true
else false
Find one of the libraries that converts dates into 'number of days since some epoch' (often called a Julian day - though there are official rules for the astronomical Julian Date, and Modified Julian Date). Then convert each date into the relevant number, and take the difference. Assuming the library handles leap years, so does your answer.
For ideas on one such set of code, see 'Calendrical Calculations'.
Convert them both to UNIX epoch time and subtract the difference.
UNIX Epoch time is the total number of seconds for a date since 1 January 1970 00:00:00.0
Once you've got the number of seconds, you divide that difference by the number of seconds in a day (which is 24 hours * 60 minutes * 60 seconds = 86400 seconds).
I would convert the two dates in Julian day and then do the difference, but I would have to check if this is a good solution with no drawbacks first. I suggest you to do the same.