此示例是一种使用 date 计算一个月最后一天的方法图书馆。 有没有更简单的解决方案来实现这个目标?
这个想法行不通: 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);
}
关于c++ - 一个月的最后一天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53920169/