noah
noah

Reputation: 107

chrono type to string c++20

I am trying to format the time into hh::mm::ss then put it in a wide-string-stream. The code is as follows.


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

        std::chrono::steady_clock::duration time_elapsed = end - start;

        std::chrono::hh_mm_ss formatted {std::chrono::duration_cast<std::chrono::milliseconds> (time_elapsed)};

start is in the constructor of the class. using the << stream operators do not work and i do not see any way to convert this type to a string.
My question is how can i convert formatted to a string (c style, wstring, or normal string)?

Upvotes: 0

Views: 890

Answers (1)

WBuck
WBuck

Reputation: 5511

The following works for me in MSVC. As of 2021-08-12 I had to use the /std:c++latest switch with Visual Studio version 16.11.2 in order for this solution to work.

const auto start{ std::chrono::steady_clock::now( ) };
std::this_thread::sleep_for( std::chrono::milliseconds{ 1000 } );
const auto end{ std::chrono::steady_clock::now( ) };

const auto elapsed{ end - start };

std::chrono::hh_mm_ss formatted{ 
    std::chrono::duration_cast<std::chrono::milliseconds>( elapsed ) };

std::cout << formatted << '\n';

// Or
std::stringstream ss{ };
ss << formatted;

std::cout << ss.str( ) << '\n';

Upvotes: 5

Related Questions