C++ to achieve two days between how many days the solution

  • 2020-04-01 23:27:28
  • OfStack

The principle of calculation is to find out the difference of days between each date and January 1 of a year, and then make further difference.


#include <stdio.h>
struct MyDate
{
 int year;
 int month;
 int day;
};
int GetAbsDays(MyDate x)
{
 int i;
 int month_day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
 int year = x.year-1;  //Because I want the distance from January 1 to 1 year
 int days = year * 365 + year/4 - year/100 + year/400;  //Find the number of previous leap years and want to add on the number of days
 if(x.year%4==0 && x.year%100!=0 || x.year%400==0) month_day[1]++; //The current year is a leap year, February plus 1
 for(i=0; i<x.month-1; i++)
  days += month_day[i];
 days += x.day-1;  //Today should not count as days
 return days;
}
int GetDiffDays(MyDate a, MyDate b)
{
 return GetAbsDays(b) - GetAbsDays(a);
}
int main(int argc, char* argv[])
{
 MyDate a = {1842,5,18};
 MyDate b = {2000,3,13};
 int n = GetDiffDays(a,b);
 printf("%dn", n);
}


Related articles: