C/C++的新版日期类型并不能获取日期的具体数值。C++20的std::chrono::month_day_last可以获取某月的最后一天,但是返回的类型是month_day_last类型,这个类型无法获取天数,只能获取月份。 所以C/C++如何获取某年月份的最后一天?C++20之前,获取年月日的数值还是得借助库,通过转换为time_t类型之后再转换为struct tm类型获取数值,功能比较弱。所以这里只需要C库的即可实现。

实际上月份的最后一天可能是28,29,30,31,它是与年份有关的,所以决定它的日期还是得通过获取系统计算出来的实际值。方法就是通过获取下一个月份的1号的日期,之后再减去固定的每日24小时即可获取前一天的日期,也就是当前月的最后一天。
我们知道time_t的时间单位是秒,而一天总共有60*60*24 = 86400秒。
std::pairMonthRange(time_t t)
{auto now = localtime(&t);
now->tm_mon++;
now->tm_mon %= 12;
now->tm_mday = 1;
auto next = mktime(now);
auto prev = next - 86400;
auto last = localtime(&prev);
char lastDay[16] = {0};
sprintf(lastDay,"%.4d-%.2d-%.2d",last->tm_year+1900,last->tm_mon+1,last->tm_mday);
char firstDay[16] = {0};
sprintf(firstDay,"%.4d-%.2d-%.2d",last->tm_year+1900,last->tm_mon+1,1);
return std::make_pair(firstDay,lastDay);
} 调用auto f1 = MonthRange(time(NULL));
cout<< f1.first.c_str()<< "=>"<< f1.second.c_str()<< endl;输出2021-12-01=>2021-12-31参考Date and time utilities - cppreference.com
time_t - cppreference.com
tm - cppreference.com
Date and time utilities - cppreference.com
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧