Fmt: printing chrono time_point

Created on 17 Dec 2018  路  2Comments  路  Source: fmtlib/fmt

I can't print a time_points.
e.g.:

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

int main(){
    // fails to compile
    fmt::print("{}", std::chrono::system_clock::now());
}

I had a look at time.h and it looks like only c style std::time is supported right now.

Does anybody now an easy handy hack to acquire formatting chrono time_points?

Otherwise, and anyways, this is also a feature request. ;)

Further, while this code succeeds:

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

int main(){
    // prints correct result
    std::time_t t = std::time(nullptr);
    fmt::print("{:%Y-%m-%d}", *std::localtime(&t));
}

this code fails to compile:

#include <fmt/format.h>
#include <fmt/time.h>
#include <fmt/chrono.h>
#include <iostream>
int main(){
    using namespace std::chrono;
    //  fails to compile
    std::time_t t = std::time(nullptr);
    std::cout << "{:%Y-%m-%d}"_format(*std::localtime(&t)) << std::endl;
}

Seems to be a bug, doesn't it?

I am using the most recent commit 3e01376e089ffcf993adeb20aea0c0019bf66ee2.

This issue questions this post in issue #864.

Most helpful comment

Right now you can format/print a duration, but not a time_point. It doesn't really make sense to directly output a time_point. This functionality isn't available in the stdlib either, though in C++20 you can do std::cout << duration, so fmtlib is already ahead of the curve. So change your code to:

fmt::print("{}", std::chrono::system_clock::now().time_since_epoch());

All 2 comments

Right now you can format/print a duration, but not a time_point. It doesn't really make sense to directly output a time_point. This functionality isn't available in the stdlib either, though in C++20 you can do std::cout << duration, so fmtlib is already ahead of the curve. So change your code to:

fmt::print("{}", std::chrono::system_clock::now().time_since_epoch());

@remyabel is right about durations and time points. Regarding your other question,

Seems to be a bug, doesn't it?

Not really, _format will give an expected compile-time error if the formatter's parse function is not constexpr which is the case with strftime formatting. You should use the normal format function instead.

Was this page helpful?
0 / 5 - 0 ratings