#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;
}
Needed to write a simple routine, to find the number of days for a given month. However, for mktime, why should I pass the actual month number instead of month number -1.
It is more confusing, that after calling mktime, the tm_mon returns month -1 instead of the original month that was passed.
Because you set
tm_mday = 0. The “zeroth” of the month (tm_mon = 2means March) rolls back to the last day of the previous month (February).Yes, it is confusing that
tm_mdayis 1-based whereastm_monis 0-based. You get used to it eventually 🙂