This question already has answers here:
calculate the days between two dates
                                
                                    (2个答案)
                                
                        
                                5个月前关闭。
            
                    
我做了一个程序,计算两个日期之间的天数不同,但是它计算的是天数和天数,但是只打印天数,例如,如果它的2个月和25天,它仅打印25天,我希望它仅以天计算,因此答案将不会是2个月零25天,而是68天。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ( int argc, char *argv[] ) {
  /* Names of the months */
  char *monthName [12] = {"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
  /* The number of days in each month */
  int monthLength[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int dd1 = 0;
  int mm1 = 0;
  int yyyy1 = 0;
  int dd2 = 0;
  int mm2 = 0;
  int yyyy2 = 0;
  int day_diff;
  if ( argc < 4 ) {
    printf ( "usage: ./daysCalculcatorA dd1 mm2 yyyy1 dd2 mm2 yyyy2 \n" );
    exit ( 1 );
  } else {
    dd1 = atoi ( argv[1] );
    mm1 = atoi ( argv[2] );
    yyyy1 = atoi ( argv[3] );
    dd2 = atoi ( argv[4] );
    mm2 = atoi ( argv[5] );
    yyyy2 = atoi ( argv[6] );
  }
  if ( dd2 < dd1)  {
    if(mm2 ==3)
    {
      if ((yyyy2 % 4 == 0 && yyyy2 % 100 != 0) || (yyyy2 % 400 == 0))  {
        dd2+=29;
    }
      else
      {
        dd2+=28;
      }
    }
    else if (mm2 ==5 || mm2 ==7 || mm2 ==10 || mm2 ==12)
    {
      dd2+=30;
    }
    else
    {
      dd2 +=31;
    }
    mm2 = mm2 -1;
  }
  if (mm2<mm1)
  {
    mm2 += 12;
    yyyy2 -= 1;
  }
  day_diff = dd2 - dd1-1;
  printf(" %d ", day_diff);
  return (0);
}

最佳答案

参见mktime示例,了解如何创建2个struct tm对象,然后可以轻松比较它们。

关于c - 计算两个日期之间的天数,但结果错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57965078/

10-12 16:10