C++ Chrono 判断一天是否是周末?

mez*_*hic 4 c++ c++-chrono

我有一个格式为年 (int)、月 (int) 和日 (int) 的日期,例如,2018 年 10 月 12 日为 2018、10、12。

有没有办法可以使用带有这些整数的 C++ Chrono 库来确定我的“日期”是否是周末?

如果不是,那么实现这一目标的最简单的替代方法是什么?

How*_*ant 5

在 C++20 中,你将能够做到这一点:

#include <chrono>

constexpr
bool
is_weekend(std::chrono::sys_days t)
{
    using namespace std::chrono;
    const weekday wd{t};
    return wd == Saturday || wd == Sunday;
}

int
main()
{
    using namespace std::chrono;
    static_assert(!is_weekend(year{2018}/10/12), "");
    static_assert( is_weekend(year{2018}/10/13), "");
}
Run Code Online (Sandbox Code Playgroud)

自然地,如果输入不是constexpr,那么计算也不能。

据我所知,还没有人发布此功能,但是您可以使用Howard Hinnant 的 datetime lib以这种语法抢先一步。您只需要将#include "date/date.h"一些更改using namespace std::chrono;using namespace date;.

#include "date/date.h"

constexpr
bool
is_weekend(date::sys_days t)
{
    using namespace date;
    const weekday wd{t};
    return wd == Saturday || wd == Sunday;
}

int
main()
{
    using namespace date;
    static_assert(!is_weekend(year{2018}/10/12), "");
    static_assert( is_weekend(year{2018}/10/13), "");
}
Run Code Online (Sandbox Code Playgroud)

这将适用于 C++17、C++14,如果删除constexpr, C++11。它不会移植到 C++11 之前,因为它确实依赖于<chrono>.

对于奖励积分,上述函数也适用于当前时间 (UTC):

    assert(!is_weekend(floor<days>(std::chrono::system_clock::now())));
Run Code Online (Sandbox Code Playgroud)