首页 > 解决方案 > boost加月的行为原理是什么?

问题描述

提升添加月份的示例

2009 年 2 月 28 日 + 1 个月 = 2009 年 3 月 31 日

#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 以获取类似的添加月份代码。

标签: c++dateboost

解决方案


的文档中提到了此行为boost::date_time::month_functor

此调整功能为基于 ymd 的日历上的“基于月份”的推进提供了逻辑。它用于处理不存在的月末日的策略是备份到月的最后一天。此外,如果开始日期是一个月的最后一天,这个函子将尝试调整到月末

因此,将一个月添加到 2 月 28 日将导致 3 月 31 日。
但是将一个月添加到 2 月 27 日将导致 3 月 27 日。

LIVE DEMO.


推荐阅读