easy way to add 1 month to a time_t in C/C++

后端 未结 4 1685
小蘑菇
小蘑菇 2021-01-13 01:51

I have some code that uses the Oracle function add_months to increment a Date by X number of months.

I now need to re-implement the same logic in a C / C++ function.

4条回答
  •  佛祖请我去吃肉
    2021-01-13 02:28

    Really new answer to a really old question!

    Using this free and open source library, and a C++14 compiler (such as clang) I can now write this:

    #include "date.h"
    
    constexpr
    date::year_month_day
    add(date::year_month_day ymd, date::months m) noexcept
    {
        using namespace date;
        auto was_last = ymd == ymd.year()/ymd.month()/last;
        ymd = ymd + m;
        if (!ymd.ok() || was_last)
            ymd = ymd.year()/ymd.month()/last;
        return ymd;
    }
    
    int
    main()
    {
        using namespace date;
        static_assert(add(30_d/01/2009, months{ 1}) == 28_d/02/2009, "");
        static_assert(add(31_d/01/2009, months{ 1}) == 28_d/02/2009, "");
        static_assert(add(27_d/02/2009, months{ 1}) == 27_d/03/2009, "");
        static_assert(add(28_d/02/2009, months{ 1}) == 31_d/03/2009, "");
        static_assert(add(31_d/01/2009, months{50}) == 31_d/03/2013, "");
    }
    

    And it compiles.

    Note the remarkable similarity between the actual code, and the OP's pseudo-code:

    30/01/2009 + 1 month = 28/02/2009
    31/01/2009 + 1 month = 28/02/2009
    27/02/2009 + 1 month = 27/03/2009
    28/02/2009 + 1 month = 31/03/2009
    31/01/2009 + 50 months = 31/03/2013

    Also note that compile-time information in leads to compile-time information out.

提交回复
热议问题