Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 398
Michael A Avatar asked Apr 23 '26 05:04

Michael A


1 Answers

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.

like image 59
Howard Hinnant Avatar answered Apr 25 '26 20:04

Howard Hinnant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!