The accepted answer is a good one, but I would like to demonstrate doing this with an open-source, third-party, date handling library:
auto now = std::chrono::system_clock::now();
std::cout << date::format("%T", std::chrono::floor<std::chrono::milliseconds>(now));
This just output, for me: 10:01:46.654
.
The fractional seconds separator is locale specific. In Sweden, where I reside, they use the comma as a separator. date::format
allows supplying a std::locale
, so we can force the use of the Swedish locale, for example, on my machine:
auto now = std::chrono::system_clock::now();
std::cout << date::format(std::locale("sv-SE"), "%T", std::chrono::floor<std::chrono::milliseconds>(now));
Now the ouput is: 10:02:32,169
.
This formatting has been accepted in C++20, so you will get this when the vendors have implemented it :)
Of course, if the "%X" formatting is really want you want, then you cannot have decimal seconds and need to append them yourself:
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch() % std::chrono::seconds{1});
std::cout << date::format("%X", std::chrono::floor<std::chrono::milliseconds>(now)) << "," << ms.count();
Note that I am using ms.count()
because in C++20 streaming a duration will append the units as well, meaning that << ms
would output something like 123ms
.