Formatting seconds in std::chrono

1 day ago 3
ARTICLE AD BOX

The leading 0 does not, and is not supposed to, impact the number of fractional digits in the seconds.

The only thing that will impact the number of fractional digits in the seconds is the type of the time_point in the argument to format().

Whatever type of system_clock-based time_point you put into format(), %S (and %T) will give you all of the information in that time_point. Full precision.

If you want more precision, switch to a finer time_point. If you want less precision, switch to a coarser time_point.

This design has the advantage that it is common to want to traffic in time_points of a given precision throughout your code, maybe seconds, maybe milliseconds, maybe microseconds. And then when you print it out, you want all of the information. You typically need to set the precision once, say when getting the current time, or at a parse input. Then multiple output statements automatically react to the type of that chosen time_point.

For example:

using TimePoint = std::chrono::sys_time<std::chrono::milliseconds>; TimePoint current_time() { using namespace std::chrono; return floor<TimePoint::duration>(system_clock::now()); } ... using namespace std::literals; auto now = current_time(); // Print out current time std::clog << std::format( "{:%T}", now ) << std::endl; // Do some computation with the time_point now += 1h; // Print out the time_point again std::clog << std::format( "{:%T}", now ) << std::endl;

In the above example, the precision for the entire program is specified to be milliseconds in one place. If and when there is a need to change the precision, that change is made in that one place, and the rest of the program, including print statements, automatically updates its behavior.

Read Entire Article