首页 > 解决方案 > 如何在 C++ 中获得一个月的第三个星期五?

问题描述

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

所以,我想知道是否有任何优雅的算法可以让我在我的情况下获得任何日期,比如 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

}

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

标签: c++date

解决方案


使用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;
}

或者

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

using namespace date;

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

推荐阅读