How to calculate the number of days between two given dates? (Obstacle in the sticky year)

  • Any year evenly divisible by 400 is a leap year (for example, 2000 was a leap year).
  • Any other year evenly divisible by 100 is not a leap year (for example, 1700, 1800 and 1900 were not leap years).
  • Any other year evenly divisible by 4 is a leap year (for example, 1996 and 2004 are leap years).

But I'm not sure how to make nested if there are states in my c-program that would give the correct answer ...

+3
source share
7 answers

Transform them into the UNIX era and subtract the difference.

UNIX Epoch time - 1 1970 00: 00: 00.0

, ( 24 * 60 * 60 = 86400 ).

+13

Julian day, , , - . .

+2

, " - " ( ), Julian ). . , , .

. " ".

+2

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
+1
source
#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;
}
+1
source

You do not need nested conventions for this.

Hint: Instead of determining whether a given year is a leap year, try to determine the total number of days of leap development that came before it.

0
source

Source: https://habr.com/ru/post/1716948/


All Articles