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

后端 未结 6 1060
情深已故
情深已故 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 
    #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;
    }
    

提交回复
热议问题