Example of a method for calculating date differences in the C language

  • 2020-05-24 05:55:56
  • OfStack

This example shows how the C language calculates date differences. I will share it with you for your reference as follows:

Historically, different human settlements may have had different calendars, making it difficult to convert dates from recorded sources. Fortunately, today we all use the AD dating method. Of course, this calendar is not easy to calculate how many days the two dates are different, but it is tolerable.

The following program calculates the difference between the two dates, both dates using the ce method.


#include <bits/stdc++.h>
using namespace std;
int to_day(int y, int m, int d)
{
  int mon[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
  int day = 0;
  int i;
  for(i=1; i<y; i++){
    day += (i%4==0 && i%100!=0 || i%400==0)? 366 : 365;
  }
  if(y%4==0 && y%100!=0 || y%400==0) mon[2]++;
  for(i=1; i<m; i++){
      day += mon[i];
  }
  return day + d;
}
int diff(int y1, int m1, int d1, int y2, int m2, int d2)
{
  int a = to_day(y1, m1, d1);
  int b = to_day(y2, m2, d2);
  return b-a;
}
int main(
{
  //int n = diff(1864,12,31,1865,1,1);
  int n = diff(1864,12,31,2012,3,18);
  printf("%d\n", n);
  return 0;
}
int n = diff(1864,12,31,2012,3,18);//  The output  53768

PS: here are some other online tools for calculating dates and days:

Online date/days calculator:
http://tools.ofstack.com/jisuanqi/date_jisuanqi

Online calendar:
http://tools.ofstack.com/bianmin/wannianli

Online lunar/solar calendar conversion tool:
http://tools.ofstack.com/bianmin/yinli2yangli

I hope this article has been helpful to you in the programming of C language.


Related articles: