Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control the displayed precision when sending `std::chrono::locale_time` to a c++ stream?

I'm almost happy with this:

const auto time = std::chrono::current_zone()->to_local(std::chrono::system_clock::now());
std::cout << time;

It prints:

2023-07-26 21:08:47.2889025

that's great, but I'd like it to print slightly less decimals, for instance:

2023-07-26 21:08:47.289

Is there some iomanip-like ways of specifying the desired precision? Something like:

std::cout << std::chrono::setprecision(3) << time;
like image 697
ThreeStarProgrammer57 Avatar asked Nov 01 '25 23:11

ThreeStarProgrammer57


1 Answers

Just floor it to milliseconds, either when you call now, or when you store it, or when you print it:

const auto time = std::chrono::current_zone()->to_local(std::chrono::system_clock::now());
std::cout << std::chrono::floor<std::chrono::milliseconds>(time);

Or use round or ceil depending on your rounding preference.

like image 112
Howard Hinnant Avatar answered Nov 03 '25 15:11

Howard Hinnant