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

后端 未结 6 1042
情深已故
情深已故 2020-12-11 20:44
  • Any year evenly divisible by 400 is a leap year (e.g., 2000 was a leap year).
  • Any other year evenly divisible by 100 is not a leap year (e.g., 1700, 1800 and
相关标签:
6条回答
  • 2020-12-11 21:11
    #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;
    }
    
    0 讨论(0)
  • 2020-12-11 21:12

    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.

    0 讨论(0)
  • 2020-12-11 21:22

    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
    
    0 讨论(0)
  • 2020-12-11 21:30

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

    0 讨论(0)
  • 2020-12-11 21:31

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

    0 讨论(0)
  • 2020-12-11 21:31

    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.

    0 讨论(0)
提交回复
热议问题