Home > Software engineering >  How to correctly display the time in the H:M:S format with std::put_time and std::chrono
How to correctly display the time in the H:M:S format with std::put_time and std::chrono

Time:12-14

I'm trying to measure the time of the function with std::chrono. But the time does not output correctly. adds 3 hours for some reason.

my code

auto begin = std::chrono::steady_clock::now();
    
for (int i = 0; i < 5; i  ) { Sleep(1000); }

auto end = std::chrono::steady_clock::now();

const std::time_t total = std::chrono::duration_cast<std::chrono::seconds>(end - begin).count();

std::stringstream ssTotal;

ssTotal << std::put_time(std::localtime(&total), "%H:%M:%S");

Output Total: 03:00:05

CodePudding user response:

The problem is that std::time_t is intended for a time point not a duration, and when you then pass it through std::localtime it tries to take your local timezone into account.

The "correct" answer is to stick to durations all the way through, but AFAIK the nice formatting and printing stuff for that is a C 20 feature that isn't widely implemented yet.

A quick workaround is to use std::gmtime instead of std::localtime, as that adjusts to the 0 timezone.

  •  Tags:  
  • c
  • Related