c++ - boost加月行为的原理是什么?

标签 c++ date boost

example of boost add month

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/

相关文章:

c++ - 使用 g++ 进行奇怪的零初始化

c++ - 不能在派生模板类中使用 struct 吗?

c++ - 在一个解决方案中使用多个 .cpp 文件的目的是什么?

php - 如何从当前日期减去前一个日期(没有编号)。 php 中的天数

mysql - 在日期之间选择mysql查询?

C++ Boost::serialization:如何在一个程序中归档一个对象并在另一个程序中恢复它?

c++ - 如何隐藏来自外部库的编译警告

java - 通过SimpleDateFormat解析系统时间报错

c++ - 如果模板类型本身就是模板,如何获取迭代器?

c++ - boost::random::variate_generator - 构造后更改参数