#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之后,tm_mon返回month -1而不是过去的原始月份。
最佳答案
因为您设置了tm_mday = 0
。该月的“零”(tm_mon = 2
表示三月)回滚到上一个月(二月)的最后一天。
是的,令人困惑的是tm_mday
是基于1的,而tm_mon
是基于0的。您最终习惯了:-)
关于c++ - 传递给mktime时,为什么应将月份号设置为实际月份?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10305937/