Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading