Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 format sys_time with milliseconds precision

I'm trying to write a time string with a millisecond precision in MSVC 19.11 with /stc:c++latest.

With this i get 7 digits accuracy, what i don't want.

auto now = std::chrono::system_clock::now();
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", now);

I tried std::cout << std::format("{0:%d.%m.%Y %H:%M:%S.3}", now); and some possibilities of std::setprecision(3) in vain.

Is there a solution to format it there or do i need to change "now"?

like image 926
Selomna Avatar asked Feb 13 '26 20:02

Selomna


1 Answers

auto now = std::chrono::floor<std::chrono::milliseconds>(std::chrono::system_clock::now());
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", now);

or:

auto now = std::chrono::system_clock::now();
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", std::chrono::floor<std::chrono::milliseconds>(now));

I.e. the precision of the output is controlled by the precision of the input.

Aside: You can also use %T in place of %H:%M:%S if desired.

like image 97
Howard Hinnant Avatar answered Feb 16 '26 09:02

Howard Hinnant