Home > Software design >  c 20 format sys_time with milliseconds precision
c 20 format sys_time with milliseconds precision

Time:12-18

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"?

CodePudding user response:

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.

  • Related