You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++作业问题:如何实现显示当前月份的天数

获取当前月份总天数的两种实现方式

你现在的问题核心是没有正确获取当月的最后一天,而是误拿了tm_mday(当前日期),另外二月的闰年判断需要结合年份来处理。下面给你两种可靠的实现方式:


方法一:利用标准库时间函数(推荐)

通过修改tm结构体的日期到下月第一天,再回退一天,就能直接拿到当月的最后一天,自动处理闰年和不同月份的天数差异:

#include <iostream>
#include <string>
#include <ctime>

using namespace std;

int main() {
    time_t epSeconds = time(NULL);
    tm* pCalendarTime = localtime(&epSeconds);
    
    string monthnames[] = {"January", "February", "March", "April", "May", "June", 
                           "July", "August", "September", "October", "November", "December"};
    
    // 复制当前时间结构体,避免修改原数据
    tm lastDay = *pCalendarTime;
    // 切换到下月第一天
    lastDay.tm_mon += 1;
    lastDay.tm_mday = 1;
    // 把时间转换为time_t,再回退86400秒(一天)
    time_t nextMonthFirst = mktime(&lastDay);
    time_t currentMonthLast = nextMonthFirst - 86400;
    // 转换回tm结构体,获取当月最后一天的日期
    tm* finalDay = localtime(&currentMonthLast);
    
    cout << "This is " << monthnames[pCalendarTime->tm_mon] << ", " << 1900 + pCalendarTime->tm_year << endl;
    cout << "Total days in this month: " << finalDay->tm_mday << endl;
    
    return 0;
}

说明:

  • mktime()会自动处理月份溢出(比如12月加1会变成下一年的1月),也会自动调整闰年的二月天数
  • 回退一天用86400秒(246060),这种方式比手动计算更稳妥,避免夏令时等特殊情况影响

方法二:手动计算(适合理解逻辑)

先定义各月份的天数,再结合闰年规则调整二月的天数:

#include <iostream>
#include <string>
#include <ctime>

using namespace std;

// 判断闰年的函数
bool isLeapYear(int year) {
    if (year % 4 != 0) return false;
    else if (year % 100 != 0) return true;
    else return (year % 400 == 0);
}

int main() {
    time_t epSeconds = time(NULL);
    tm* pCalendarTime = localtime(&epSeconds);
    
    string monthnames[] = {"January", "February", "March", "April", "May", "June", 
                           "July", "August", "September", "October", "November", "December"};
    // 非闰年各月份天数
    int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
    
    int currentYear = 1900 + pCalendarTime->tm_year;
    int currentMonth = pCalendarTime->tm_mon;
    int totalDays = monthDays[currentMonth];
    
    // 如果是二月且是闰年,加1天
    if (currentMonth == 1 && isLeapYear(currentYear)) {
        totalDays += 1;
    }
    
    cout << "This is " << monthnames[currentMonth] << ", " << currentYear << endl;
    cout << "Total days in this month: " << totalDays << endl;
    
    return 0;
}

说明:

  • 闰年判断规则:能被4整除但不能被100整除,或者能被400整除
  • 月份索引tm_mon从0开始(0=1月,1=二月),所以二月对应的索引是1

你之前只拿到今日日期是因为直接用了pCalendarTime->tm_mday,这个字段存储的是当前的日,不是当月总天数,上面两种方法都能解决这个问题,同时处理闰年二月的特殊情况。

内容的提问来源于stack exchange,提问作者SolidSnake212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:43:17