我正在尋找一種方法來查找兩個日期之間的差異。解決方案需要考慮閏年。請參閱以下兩段代碼。 2012年是閏年,而2013年並非如此,所以我不明白爲什麼兩個計劃都會輸出「32天差距」。如果time.h確實考慮了閏年,它們肯定會有所不同。是否time.h允許閏年C
第一:
#include <stdio.h>
#include <time.h>
int main()
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
double days;
start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 2; start_date.tm_mday = 1; start_date.tm_year = 112;
end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 3; end_date.tm_mday = 1; end_date.tm_year = 112;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
days = difftime(end_time, start_time)/86400;
printf ("%.f days difference\n", days);
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 days;
start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 2; start_date.tm_mday = 1; start_date.tm_year = 113;
end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 3; end_date.tm_mday = 1; end_date.tm_year = 113;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
days = difftime(end_time, start_time)/86400;
printf ("%.f days difference\n", days);
return 0;
}
要小心,因爲你將結構聲明爲局部變量,但不要初始化它們中的所有字段。這意味着未初始化字段的值將是不確定的,並且'mktime'調用的結果將是未定義的。 –
另請注意,您輸入的月份是三月和四月。 'tm_mon'成員字段是基於零的,其中一個是二月,二是三月。見例如[此參考資料](http://en.cppreference.com/w/c/chrono/tm)。 –
@JoachimPileborg非常感謝你,那是我認爲的錯誤,它現在起作用。但是,我不是很瞭解你的第一個評論,你能擴展嗎? – Jamie1596