I'm just trying to print the current weekday (local time) using C++20 std::chrono.
Seems easy enough (one, two, three):
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono;
system_clock::time_point now = system_clock::now();
// system_clock::time_point now = sys_days{June / 26d / 2023y} + 12h;
weekday wd{floor<days>(now)};
#ifdef _WIN32
std::cout << wd << "\n";
#else
std::cout << wd.c_encoding() << " (Sunday = " << Sunday.c_encoding() << ")\n";
#endif
return 0;
}
However, this prints Tue
for me (it's monday). If I switch the comment to the manually-defined date (this question posted on June 26th 2023 -0400), it prints Mon
.
How do I do this correctly for the current date?
Why is the
now()
date behaving differently than thesys_days
/year_month_day
one?
Edit: I believe this is a time-zone thing, as my three link suggests. I can't get this to compile with std::chrono
though:
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono;
auto now = std::chrono::system_clock::now();
auto now_local = zoned_time{current_zone(), now}.get_local_time();
sys_days now_local_in_days{floor<days>(now_local)}; // !!! no constructor available
weekday wd{now_local_in_days};
#ifdef _WIN32
std::cout << wd << "\n";
#else
std::cout << wd.c_encoding() << "\n";
#endif
return 0;
}
So I guess I'm adding:
- How do I convert a local_time to a weekday?