28/02/2009 + 1 month = 31/03/2009
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/gregorian/formatters.hpp>
#include <iostream>
using namespace boost::gregorian;
using namespace std;
int main()
{
typedef boost::date_time::month_functor<date> add_month;
date d(2019, Feb, 28);
add_month mf(1);
date d2 = d + mf.get_offset(d);
cout << to_simple_string(d2) << endl;//output:2019-Mar-31
}
输出是 2019-Mar-31 而不是 2019-Mar-28。这种行为的理论基础是什么?谈论它在 C# 和 delphi 中输出 2019-Mar-28 以获取类似的添加月份代码。
最佳答案
boost::date_time::month_functor
的文档中提到了此行为.
This adjustment function provides the logic for 'month-based' advancement on a ymd based calendar. The policy it uses to handle the non existant end of month days is to back up to the last day of the month. Also, if the starting date is the last day of a month, this functor will attempt to adjust to the end of the month.
因此,将 2 月 28 日加一个月将得到 3 月 31 日。
但是在 2 月 27 日上加一个月将得到 3 月 27 日。
参见 LIVE DEMO.
关于c++ - boost加月行为的原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56123140/