c++ - 一个月的最后一天?

标签 c++ date

此示例是一种使用 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/

相关文章:

c++ - 计算给定数组的子序列数,使得它们的总和小于或等于给定数?

c++ - 如何使用正则表达式中的 sscanf() 解析字符串?

R:如何通过前一天的信息改变证券交易所日指数时间序列的缺口(假期)?

android - 在 Android Studio 上使用 Calendar.getInstance() 时如何插入和填充日期时间

javascript - 在我的示例中如何将值插入数组?

android - 强制 Android DateUtils.getRelativeDateTimeString() 忽略设备区域设置?

Android Studio 找不到 Boost header

c++ - 当设置 ItemIsMovable 标志时,子项在 QGraphicsView 中不可移动

c++ - 在 linux 中的 c++ 程序中设置系统日期和时间

c++ - "extern"关键字使用