如何在 C++ 中获得一个月的第三个星期五?

xyh*_*ang 2 c++ date

我认为日期处理有点复杂。

所以,我想知道是否有任何优雅的算法可以在我的条件下获得任何日期,例如 2020 年 9 月的第三个星期五的日期?

让我们指定我想要的两种方法:

int get_date(int month, int weekday, int no) {  // for example: get_date(202009, 3, 3)
     //  should return the third wednesday in sep 2020, it's 20200917
}

int date_sub(int date1, int date2) { // for example:
   // date_sub(20200928, 20200925) should return 3

}
Run Code Online (Sandbox Code Playgroud)

我知道 boost 有一些不错的东西,但我认为它可能太重了,有没有更好的选择?

Ala*_*les 6

使用c++20 日期支持Howard Hinnants 实现,这是微不足道的:

#include <chrono>
#include <iostream>

using namespace std::chrono;

int main()
{
    constexpr year_month_day date {year(2020)/September/Friday[3]};
    std::cout << date;
}
Run Code Online (Sandbox Code Playgroud)

或者

#include "date.h"
#include <iostream>

using namespace date;

int main()
{
    constexpr year_month_day date {year(2020)/September/Friday[3]};
    std::cout << date;
}
Run Code Online (Sandbox Code Playgroud)