Skip to content

Commit

Permalink
Add formatters for chrono::time_point<system_clock> (#1837)
Browse files Browse the repository at this point in the history
Add formatters for chrono::time_point and helper overloads for localtime/gmtime(time_point)
Fixes #1819
  • Loading branch information
adamburgess authored Aug 28, 2020
1 parent 77b627b commit f39e6fb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,11 @@ inline std::tm localtime(std::time_t time) {
return lt.tm_;
}

inline std::tm localtime(
std::chrono::time_point<std::chrono::system_clock> time_point) {
return localtime(std::chrono::system_clock::to_time_t(time_point));
}

// Thread-safe replacement for std::gmtime
inline std::tm gmtime(std::time_t time) {
struct dispatcher {
Expand Down Expand Up @@ -361,6 +366,11 @@ inline std::tm gmtime(std::time_t time) {
return gt.tm_;
}

inline std::tm gmtime(
std::chrono::time_point<std::chrono::system_clock> time_point) {
return gmtime(std::chrono::system_clock::to_time_t(time_point));
}

namespace detail {
inline size_t strftime(char* str, size_t count, const char* format,
const std::tm* time) {
Expand All @@ -373,6 +383,17 @@ 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 FormatContext>
auto format(std::chrono::time_point<std::chrono::system_clock> val,
FormatContext& ctx) -> decltype(ctx.out()) {
std::tm time = localtime(val);
return formatter<std::tm, Char>::format(time, ctx);
}
};

template <typename Char> struct formatter<std::tm, Char> {
template <typename ParseContext>
auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
Expand Down
11 changes: 11 additions & 0 deletions test/chrono-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,17 @@ TEST(TimeTest, GMTime) {
EXPECT_TRUE(EqualTime(tm, fmt::gmtime(t)));
}

TEST(TimeTest, TimePoint) {
std::chrono::system_clock::time_point point = std::chrono::system_clock::now();

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), "It is %Y-%m-%d %H:%M:%S", &tm);

EXPECT_EQ(strftime_output, fmt::format("It is {:%Y-%m-%d %H:%M:%S}", point));
}

#define EXPECT_TIME(spec, time, duration) \
{ \
std::locale loc("ja_JP.utf8"); \
Expand Down

0 comments on commit f39e6fb

Please sign in to comment.