-1

我做了一个简单的程序来计算两天之间的天数:

#include <stdio.h>
#include <iostream>
#include <ctime>
#include <utility>

using namespace std;
int main(){
    struct tm t1 = {0,0,0,28,2,104};
    struct tm t2 = {0,0,0,1,3,104};
    time_t x = mktime(&t1);
    time_t y = mktime(&t2);
    cout << difftime(y,x)/3600/24 << endl;

}

输出是 4 但是,我的预期结果是 1。我可以知道问题出在哪里吗?

4

1 回答 1

4

在 astruct tm中,月份从011(不是112)计算,因此2是三月和3四月,您的代码输出从 3 月 28到 4 月 1之间的天数,即 4。

正确的版本是:

struct tm t1 = {0, 0, 0, 28, 1, 104};
struct tm t2 = {0, 0, 0,  1, 2, 104};

顺便说一句,2004 年是闰年,因此 2 月有 29 天,2 月 28和 3 月 1日之间有两天(不是一天)。

difftime02/28/2004 00:00:00为您提供和之间的秒数03/01/2004 00:00:00(第一天计入差异)。

于 2016-03-17T16:18:04.770 回答