为什么在传递给 mktime 时,我应该将月份数字设置为实际月份

Why should I set the month number to the actual month when passing to mktime?

本文关键字:数字 设置 我应该 mktime 为什么      更新时间:2023-10-16
#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返回月份 -1 而不是经过的原始月份。

因为你设置了tm_mday = 0 .该月的"零日"(tm_mon = 2表示三月)回滚到上个月的最后一天(二月)。

是的,令人困惑的是,tm_mday是基于 1 的,而tm_mon是基于 0 的。你最终会习惯的:-)