intrigued_66
intrigued_66

Reputation: 17268

C++ Chrono determine whether day is a weekend?

I have a date in the form year (int), month (int) and day (int), for example, 2018, 10, 12 for October 12th, 2018.

Is there a way I can use C++ Chrono library with these integers to determine whether my "date" is a weekend day?

If not, what would be the simplest alternative way to achieve this?

Upvotes: 6

Views: 2396

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 219428

In C++20, you will be able to do this:

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

Naturally if the input isn't constexpr, then the computation can't be either.

No one that I'm aware of is yet shipping this, however you can get a head start with this syntax using Howard Hinnant's datetime lib. You just need to #include "date/date.h" and change a few using namespace std::chrono; to 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), "");
}

This will work with C++17, C++14, and if you remove the constexpr, C++11. It won't port to earlier than C++11 as it does depend on <chrono>.

For bonus points, the above function will also work with the current time (UTC):

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

Upvotes: 8

Related Questions