一个月的最后一天? [英] Last day of a month?

查看:59
本文介绍了一个月的最后一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例是一种使用 date 来计算一个月的最后一天的方法.图书馆.为此目标有更简单的解决方案吗?

This example is a way to calculate the last day of a month using date library. Is there a simpler solution to this goal?

这个想法行不通:lastDay = firstDay + months {1}-days {1};

this idea not work: 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;
}

推荐答案

这是一种更简单的方法:

Here's an easier way:

#include "date/date.h"
#include <iostream>

date::year_month_day
lastDay(date::year_month_day ymd)
{
    return ymd.year()/ymd.month()/date::last;
}

int
main()
{
    using namespace date;
    std::cout << lastDay(2018_y/12/01) << '\n';  // 2018-12-31
}

last 可以在任何年/月/日表达式中用作日指定符",以表示"年/月的最后一天 year_month_day_last 的类型,该类型可以隐式转换为 year_month_day .它还具有一个 day() getter:

last can be used as the "day specifier" in any year/month/day expression to mean "last day of the year/month pair. This will create a type year_month_day_last which is implicitly convertible to year_month_day. It also has a day() getter:

https://howardhinnant.github.io/date/date.html#year_month_day_last

这篇关于一个月的最后一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆