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

fmt format %H:%M:%S without decimals

I am trying to format a std::chrono::duration object to the format HH:MM::SS, e.g. 16:42:02 being the hours (16), the minutes (42), and the seconds (2).

the library fmt offers useful formatting specifiers for this:

using namespace std::chrono;

auto start = high_resolution_clock::now();
auto end = start + 4s;
fmt::print("{:%H:%M:%S} \n", end);

which unfortuantely prints the seconds in decimals

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

16:58:55.359425076 

I want to round this to the nearest integer, but cannot figure out where to place the precision specifier (precision 2 merely test-wise):

fmt::print("{:.2%H:%M:%S} \n", end);  // error
fmt::print("{:.2f%H:%M:%S} \n", end);  // error 
fmt::print("{:%H:%M:.2%S} \n", end);  // nonsense: 17:07:.202.454873454 

I am a bit lost staring at the details of the formatspec for chrono…

A compiler explorer example of the above is here.

>Solution :

To round to the nearest second, convert your time point to seconds precision using round<seconds>(tp). Also, high_resolution_clock has no portable relationship to the calendar. You need to use system_clock instead. For gcc, high_resolution_clock is a type alias of system_clock, so it works by accident. But this will fail to compile using MSVC or LLVM tools.

#include <fmt/chrono.h>
#include <fmt/format.h>

#include <chrono>
#include <iostream>
#include <thread>
#include <vector>

int main() {
    using namespace std::chrono;

    auto start = round<seconds>(system_clock::now());
    auto end = start + 4s;
    fmt::print("{:%H:%M:%S} \n", end);
}

Demo.

If you would like other rounding modes you can use floor or ceil as well.

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