Skip to content

Commit

Permalink
Add support for time points with arbitrary durations (fmtlib#2208)
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed Apr 2, 2021
1 parent dac42f5 commit 06b3a10
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
6 changes: 3 additions & 3 deletions include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -401,9 +401,9 @@ inline size_t strftime(wchar_t* str, size_t count, const wchar_t* format,
}
} // namespace detail

template <typename Char>
struct formatter<std::chrono::time_point<std::chrono::system_clock>, Char>
: formatter<std::tm, Char> {
template <typename Char, typename Duration>
struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
Char> : formatter<std::tm, Char> {
template <typename FormatContext>
auto format(std::chrono::time_point<std::chrono::system_clock> val,
FormatContext& ctx) -> decltype(ctx.out()) {
Expand Down
28 changes: 17 additions & 11 deletions test/chrono-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -100,24 +100,30 @@ TEST(TimeTest, FormatTM) {
std::time_t t = std::chrono::system_clock::to_time_t(point);
std::tm tm = *std::localtime(&t);
char strftime_output[256];
std::strftime(strftime_output, sizeof(strftime_output),
"%Y-%m-%d %H:%M:%S", &tm);
std::strftime(strftime_output, sizeof(strftime_output), "%Y-%m-%d %H:%M:%S",
&tm);
EXPECT_EQ(strftime_output, fmt::format("{:%Y-%m-%d %H:%M:%S}", tm));
auto wstrftime_output = std::wstring();
std::copy(strftime_output, strftime_output + strlen(strftime_output),
std::back_inserter(wstrftime_output));
EXPECT_EQ(wstrftime_output,
fmt::format(L"{:%Y-%m-%d %H:%M:%S}", tm));
EXPECT_EQ(wstrftime_output, fmt::format(L"{:%Y-%m-%d %H:%M:%S}", tm));
}

TEST(TimeTest, TimePoint) {
auto point = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(point);
template <typename TimePoint> std::string strftime(TimePoint tp) {
std::time_t t = std::chrono::system_clock::to_time_t(tp);
std::tm tm = *std::localtime(&t);
char strftime_output[256];
std::strftime(strftime_output, sizeof(strftime_output),
"%Y-%m-%d %H:%M:%S", &tm);
EXPECT_EQ(strftime_output, fmt::format("{:%Y-%m-%d %H:%M:%S}", point));
char output[256];
std::strftime(output, sizeof(output), "%Y-%m-%d %H:%M:%S", &tm);
return output;
}

TEST(TimeTest, TimePoint) {
auto t1 = std::chrono::system_clock::now();
EXPECT_EQ(strftime(t1), fmt::format("{:%Y-%m-%d %H:%M:%S}", t1));
using time_point =
std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>;
auto t2 = time_point(std::chrono::seconds(42));
EXPECT_EQ(strftime(t2), fmt::format("{:%Y-%m-%d %H:%M:%S}", t2));
}

#define EXPECT_TIME(spec, time, duration) \
Expand Down

0 comments on commit 06b3a10

Please sign in to comment.