user133466
user133466

Reputation: 3415

How to calculate the number of days between two given dates? (Leap year obstacle)

But I'm not sure how to make nested if states in my c-program that would produce the right answer...

Upvotes: 4

Views: 7531

Answers (6)

Rap
Rap

Reputation: 7292

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).

Upvotes: 13

Robert L
Robert L

Reputation: 1947

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.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754650

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'.

Upvotes: 2

Christoph
Christoph

Reputation: 169713

#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;
}

Upvotes: 1

Stefano Borini
Stefano Borini

Reputation: 143895

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.

Upvotes: 2

shufler
shufler

Reputation: 932

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

Upvotes: 1

Related Questions