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())));