Qt C++代码获取每个月的天数
时间: 2024-10-07 08:02:48 浏览: 113
在Qt C++中,你可以利用标准库中的<ctime>
头文件来获取每个月的天数。以下是一个简单的示例,展示如何计算某个月份的天数:
#include <iostream>
#include <ctime>
int main() {
// 设定日期和月份 (注意:月份从0开始计数)
int month = 1; // 例如1代表一月
int year = 2023;
// 创建一个tm结构体,并设置年、月、日为无效值
std::tm t = {0};
t.tm_year = year - 1900; // 标准库使用公元纪元,需要减去1900
t.tm_mon = month - 1;
t.tm_mday = 1; // 初始设定为第一天
// 使用localtime函数将时间转换到本地时间表示,然后更新日
std::localtime(&t);
// 调整到月底,增加月份的天数
for (int i = 1; i <= 31; ++i) {
if (std::mktime(&t) == -1) break; // 如果失败,说明已经到达该月的最大天数
if (t.tm_mon + 1 == month) { // 当月的最后一天
std::cout << "The number of days in " << month << "/" << year << " is " << i << std::endl;
break;
}
}
return 0;
}
这个程序会找到给定年月的最后一个日子,并打印出它的天数。
相关推荐


















