3

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
}

The output is 2019-Mar-31 rather than 2019-Mar-28. What is theoretical basis for this behavior? Talk about it outputs 2019-Mar-28 in both C# and delphi for the similar add month code.

P.W
  • 26,289
  • 6
  • 39
  • 76
Zhang
  • 3,030
  • 2
  • 14
  • 31

1 Answers1

7

This behavior is mentioned in the documentation of 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.

So adding a month to February 28th will result in March 31st.
But adding a month to February 27th will result in March 27th.

See LIVE DEMO.

P.W
  • 26,289
  • 6
  • 39
  • 76