c++c++-chrono

How to get std::chrono::year_month_day of today?


For reference, I'm in GMT+1. I set my system clock to 0:13 am today (nov 15th 2024). Trying the canonical code from cppreference:

const std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
const std::chrono::year_month_day ymd{ std::chrono::floor<std::chrono::days>(now) };

gives me November 14th (which is wrong).

I was able to get it working correctly by using the ancient time.h functions, but that's a pretty disappointing solution.


Solution

  • You can convert the sys_time to local_time with std::chrono::current_zone()->to_local(now). Then you can convert the local_time to year_month_day.

    const auto now = std::chrono::system_clock::now();
    const auto local_now = std::chrono::current_zone()->to_local(now);
    const std::chrono::year_month_day ymd{ std::chrono::floor<std::chrono::days>(local_now) };