Does fmt library handle printing std::chrono::time_point?
Asked Answered
A

1

5

An earlier version of the documentation for the C++ {fmt} libary said, about the "chrono format specifiers":

Specifiers that have a calendaric component such as 'd' (the day of month) are valid only for std::tm and not durations or time points.

But, I can create std::chrono::time_point and print it using %d and other letters.

using std::chrono::system_clock;
using std::chrono::time_point;

time_point<system_clock> t = system_clock::now();
fmt::print("{:%Y-%m-%d %H:%M:%S}", t);
// Prints: 2022-09-08 21:27:08

Maybe I'm not understanding the docs; I'm not 100% sure about the meaning of some of the terms, like "calendaric component".

I just want to print a time point in ISO 8601 format (YYYY-mm-ddTHH:MM:SSZ) and for some reason this does not seem to be available in the standard library along with the chrono types.

Is printing a time_point (like I did above) supported?

Agbogla answered 9/9, 2022 at 3:31 Comment(0)
O
8

This part of the documentation was a bit outdated. With recent versions of {fmt} you can use d and similar format specifiers with time_point, e.g.

#include <fmt/chrono.h>

int main() {
  using std::chrono::system_clock;
  using std::chrono::time_point;
  time_point<system_clock> t = system_clock::now();
  fmt::print("{:%Y-%m-%d %H:%M:%S}", t);
}

godbolt

Oberon answered 9/9, 2022 at 16:52 Comment(1)
This seems to work only for a time_point<system_clock>. For a time_point<file_clock> tpfc, you can do file_clock::to_sys(tpfc).Gwenny

© 2022 - 2024 — McMap. All rights reserved.