计算从键盘输入的两个日期之间的天数

Count days between 2 dates input from keyboard

我是初学者,我想计算两个日期之间有多少天,但我对time.h不太了解,有人可以指出我的错误吗?因为 sec = 0 后被打印出来。谢谢。

#include <stdio.h>
#include <time.h>

main(){



    double sec;

    struct tm BD;
        BD.tm_mday;        
        BD.tm_mon;         
        BD.tm_year;

    struct tm KT;
        KT.tm_mday;        
        KT.tm_mon;         
        KT.tm_year;

    printf("Start date: ");
    scanf("%d %d %d",&BD.tm_mday,&BD.tm_mon,&BD.tm_year);

    printf("End date: ");
    scanf("%d %d %d",&KT.tm_mday,&KT.tm_mon,&KT.tm_year);

    sec = difftime(mktime(&KT),mktime(&BD));

    printf("%f",sec); 

// date= sec/86400 //

    return 0;
}

请试试这个例子。您需要将时钟设置为午夜并将结果四舍五入为整数,则计算正确:

#include <stdio.h>
#include <time.h>
int main () {
    struct tm start_date;
    struct tm end_date;
    time_t start_time, end_time;
    double seconds;
    printf("Start date: ");
    scanf("%d %d %d",&start_date.tm_mday ,&start_date.tm_mon,&start_date.tm_year);
    printf("End date: ");
    scanf("%d %d %d",&end_date.tm_mday,&end_date.tm_mon,&end_date.tm_year);
    start_date.tm_hour = 0;  start_date.tm_min = 0;  start_date.tm_sec = 0;
    end_date.tm_hour = 0;  end_date.tm_min = 0;  end_date.tm_sec = 0;
    start_time = mktime(&start_date);
    end_time = mktime(&end_date);
    seconds = difftime(end_time, start_time);
    printf ("%d days difference\n", (int) (0.5 + seconds/(60*60*24)));
    return 0;
}

测试

Start date: 23 11 2017
End date: 27 11 2017
4 days difference

代码在调用 mktime() 之前无法设置所需的字段。结果:未定义的行为。

struct tm BD;

// these 3 lines of code do nothing
BD.tm_mday;        
BD.tm_mon;         
BD.tm_year;

scanf("%d %d %d",&BD.tm_mday,&BD.tm_mon,&BD.tm_year);
// Only 3 of the 9+ fields of `BD` have a defined value.

而是首先将结构归零并设置 tm_isdst。要正确使用 mktime(),需要首先设置除 tm_ydaytm_wday 之外的所有字段。阅读时将忽略这 2 个字段。所有字段都更新为其主要范围。

由于 struct tm 可能有超过定义的 9 个字段集,因此很容易首先将整个结构的字段初始化为零以确保设置 所有 字段.程序员经常忘记设置 tm_isdst 和其他可选字段,导致结果不一致。

#include <stdio.h>
#include <time.h>

int main(void) {
  struct tm BD = { 0 };
  // Set to -1 to direct mktime() to decide if DST applies or not.
  // or set to 0, or 1, if a specific DST flag is desired.
  BD.tm_isdst = -1; 
  struct tm KT = { 0 };
  KT.tm_isdst = -1; 

  printf("Start date: ");
  if (3 != scanf("%d %d %d", &BD.tm_mday, &BD.tm_mon, &BD.tm_year)) return -1;

  printf("End date: ");
  if (3 != scanf("%d %d %d", &KT.tm_mday, &KT.tm_mon, &KT.tm_year)) return -1;

  double sec = difftime(mktime(&KT), mktime(&BD));

  printf("%f\n", sec);
  return 0;
}