2012-04-24 33 views
1
#include <time.h> 
#include <iostream> 
int main() 
{ 

     struct tm dayofmonth = {0}; 
     int iYear = 2012; 
     int iMonth = 2; // February 

     dayofmonth.tm_year = iYear - 1900; 
     dayofmonth.tm_mon = iMonth; 
     dayofmonth.tm_mday = 0; 
     dayofmonth.tm_isdst = 0; 

     mktime(&dayofmonth); 

     std::cout << "Number of days for the month " << dayofmonth.tm_mon << " is " << dayofmonth.tm_mday << std::endl; 

} 

需要寫一個簡單的例程,找到給定月份的天數。但是,對於mktime,爲什麼我應該傳遞實際的月份編號而不是月份編號-1。爲什麼要將月份數設置爲傳遞給mktime的實際月份?

更令人困惑的是,在調用mktime之後,tm_mon會返回月-1而不是傳遞的原始月份。

+0

但是,如果我不通過tm_mday爲0,那麼我不會得到該月的總天數。 – user373215 2012-04-24 21:14:08

回答

6

因爲你設置了tm_mday = 0。月份的「第零」(tm_mon = 2表示3月份)回滾到上個月(2月)的最後一天。

是的,令人困惑的是tm_mday是基於1的,而tm_mon是基於0的。你最終習慣它:-)

+0

明白了。謝謝史蒂夫。 – user373215 2012-04-24 21:14:34

相關問題