Is there a convenient way to format std::chrono::duration
to a specified format?
std::chrono::high_resolution_clock::time_point now, then;
then
Here is a possible solution using a variadic template.
The if constexpr () makes it c++17 only but replacing with a regular if still works and is c++14 compliant.
template
std::string formatDuration(DurationIn d)
{
auto val = std::chrono::duration_cast(d);
string out = std::to_string(val.count());
if constexpr(sizeof...(RestDurations) > 0) {
out += "::" + formatDuration(d - val);
}
return out;
}
template
std::string formatDuration(DurationIn) { return {}; } // recursion termination
testing in main, outputs "77::600::42"
auto formattedStr = formatDuration<
std::chrono::microseconds,
std::chrono::seconds,
std::chrono::milliseconds,
std::chrono::microseconds>(77'600'042us);