Advertisement

C++ current date and time using std::chrono uses wrong time zone

Started by July 11, 2023 04:09 PM
1 comment, last by Alundra 1 year, 5 months ago

Hi everybody,
Here is the code I use, which works perfectly except the time zone is not correct:

const std::chrono::system_clock::time_point systemClockCurrentTime = std::chrono::zoned_time(std::chrono::current_zone(), std::chrono::system_clock::now());
const std::chrono::sys_days startOfDay = std::chrono::floor<std::chrono::days>(systemClockCurrentTime);
const std::chrono::year_month_day date = std::chrono::year_month_day(startOfDay);
const std::chrono::hh_mm_ss time = std::chrono::hh_mm_ss(std::chrono::floor<std::chrono::seconds>(systemClockCurrentTime - startOfDay));

When I print the date, it's correct, but the time is using UTC where my local time is UTC+2.
I use on the start of the code std::chrono::zoned_time and std::chrono::current_zone but it does not help.
Thank you for the help to understand what is wrong!

I just found the fix, it was needed to use get_local_time:

const auto systemClockCurrentTime = std::chrono::zoned_time(std::chrono::current_zone(), std::chrono::system_clock::now()).get_local_time();
Advertisement

This topic is closed to new replies.

Advertisement