标准库无直接获取当月天数函数,需用std::mktime归一化计算:先设当月1日时间戳,再加1月得下月1日时间戳,差值除86400即天数;关键要设tm_isdst=-1并确保两次mktime间tm结构体字段正确复位。

如何用 std::chrono 和 std::time_t 获取当前月份天数
标准库没有直接返回“某月多少天”的函数,但可以靠日期推算:先拿到当前年月,再尝试构造下个月的第 1 天,减去当前月第 1 天,就能得到天数。关键在于避免手动写闰年逻辑或月份天数表。
实操建议:
- 用
std::chrono::system_clock::now()获取当前时间点 - 转成
std::time_t,再用std::localtime解析为std::tm - 把
tm_mday设为 1,再用std::mktime归一化(它会自动处理跨月/跨年) - 把
tm_mon加 1,再调一次std::mktime得到下月 1 日的时间戳 - 两个时间戳相减,除以
86400(秒/天),就是当月天数
为什么不能直接查月份天数表
因为 2 月天数取决于是否闰年,而闰年规则是:能被 4 整除但不能被 100 整除,或者能被 400 整除。硬编码 {31,28,31,...} 会漏掉 2 月的动态性,导致 2000 年、2100 年等场景出错。
常见错误现象:
立即学习“C++免费学习笔记(深入)”;
- 写死
days_in_month[1] = 28,遇到 2000 年返回 28 而非 29 - 只判断
year % 4 == 0,把 1900 年误判为闰年 - 忽略
std::tm的tm_mon是 0–11,tm_year是距 1900 年的偏移量,导致 mktime 输入非法值后返回 -1
std::mktime 的归一化行为必须依赖
std::mktime 不只是转换时间结构体,它会修正越界字段:比如把 tm_mon = 12 自动转成下一年 1 月;把 tm_mday = 0 转成上月最后一天。这个特性是安全计算跨月天数的基础。
使用时注意:
- 调用前必须把
tm_isdst设为-1,让系统自动判断夏令时,否则可能因时区歧义导致结果偏差 - 两次
std::mktime调用之间,要重新用std::localtime或手动重置tm_wday/tm_yday等字段,否则残留值会影响第二次归一化 - 返回值为
std::time_t(-1)表示失败,需检查输入合法性(如年份过小、指针为空)
完整可运行片段(仅标准库)
#include <ctime>
#include <iostream><p>int days_in_current_month() {
auto now = std::time(nullptr);
auto* tm_ptr = std::localtime(&now);
if (!tm_ptr) return -1;</p><pre class="brush:php;toolbar:false;">std::tm t = *tm_ptr;
t.tm_hour = t.tm_min = t.tm_sec = 0;
t.tm_mday = 1;
t.tm_isdst = -1;
auto first_of_month = std::mktime(&t);
if (first_of_month == std::time_t(-1)) return -1;
t.tm_mon += 1;
auto first_of_next_month = std::mktime(&t);
if (first_of_next_month == std::time_t(-1)) return -1;
return static_cast<int>((first_of_next_month - first_of_month) / 86400);}
// 调用示例 // std::cout
真正容易被忽略的是 tm_isdst = -1 和两次 std::mktime 间对 std::tm 的复位——不这么做,在某些时区或夏令时切换日附近,结果可能差 1 天。


















