c++ - 一个月的最后一天?
问题描述
这个例子是一种使用日期库计算一个月最后一天的方法。这个目标有更简单的解决方案吗?
这个想法行不通:lastDay = firstDay + months{1} - days{1};
#include <date/date.h>
#include <iostream>
using namespace std;
using namespace date;
int main() {
sys_days firstDay, lastDay;
string d1;
d1 = "2018-12-01";
istringstream in1{d1};
in1 >> parse ("%F", firstDay);
sys_days d2 = firstDay;
auto ymd = year_month_day{d2};
unsigned j = unsigned (ymd.month());
unsigned i = j;
if (i == 12)
i = 0;
while (true) {
d2 = d2 + days{1};
ymd = year_month_day{d2};
j = unsigned (ymd.month());
if (j == i + 1)
break;
}
lastDay = d2 - days{1};
cout << lastDay << '\n'; // 2018-12-31
return 0;
}
解决方案
只需创建自己的 last_day_of_month 方法:
#include <chrono>
template <class Int>
constexpr
bool
is_leap(Int y) noexcept
{
return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}
constexpr
unsigned
last_day_of_month_common_year(unsigned m) noexcept
{
constexpr unsigned char a[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
return a[m - 1];
}
template <class Int>
constexpr
unsigned
last_day_of_month(Int y, unsigned m) noexcept
{
return m != 2 || !is_leap(y) ? last_day_of_month_common_year(m) : 29u;
}
int main()
{
auto dayofmonth = last_day_of_month(2018, 6);
}
推荐阅读
- sonarqube - 为什么我们必须在 Azure DevOps 中执行 SonarQube 代码分析之前先构建项目?
- ios - 在collectionView.deleteItems 之后没有调用cellForItemAt
- javascript - 对通过函数传递的对象使用@param
- python-3.x - “模块”对象不可调用,模块“sklearn.linear_model”没有属性“适合”错误
- geolocation - 如何计算给定中心和方位角的扇区点的地理坐标
- javascript - 如何将 socket.io 实例传递给 typegraphql 解析器?
- android - Android Studio 应用程序中的 MQTT 连接错误
- firebase - 如何在颤动中滚动时修复小部件的位置不移动
- node.js - 为什么 gitup-pages 没有为我的项目加载我的所有文件?
- java - Apache Ant java 目标中的 maxmemory 标志究竟是做什么的?