簡體   English   中英

C ++ Chrono確定一天是周末嗎?

[英]C++ Chrono determine whether day is a weekend?

我的格式為年(int),月(int)和日(int),例如2018年10月12日的2018,10,12。

有沒有辦法我可以使用這些整數的C ++ Chrono庫來確定我的“約會”是否是周末?

如果沒有,那么實現這一目標的最簡單的替代方法是什么?

在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), "");
}

當然,如果輸入不是constexpr ,那么計算也不能。

我所知道的還沒有人發布這個,但是你可以使用Howard Hinnant的datetime lib從這個語法開始。 你只需#include "date/date.h"using namespace std::chrono;更改一些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), "");
}

這將適用於C ++ 17,C ++ 14,如果你刪除constexpr ,C ++ 11。 它不會比C ++ 11更早地移植到它,因為它依賴於<chrono>

對於獎勵積分,上述功能也適用於當前時間(UTC):

    assert(!is_weekend(floor<days>(std::chrono::system_clock::now())));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM