Skip to content

Commit

Permalink
Support formatting of std time_point with utc_clock
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickroocks committed Sep 23, 2022
1 parent 0b5cb18 commit b512318
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
26 changes: 26 additions & 0 deletions include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@

FMT_BEGIN_NAMESPACE

// check if std::chrono::utc_timestamp is available
#ifndef FMT_USE_UTC_TIME
# ifdef __cpp_lib_chrono
# define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L)
# endif
#endif

// Enable tzset.
#ifndef FMT_USE_TZSET
// UWP doesn't provide _tzset.
Expand Down Expand Up @@ -2014,6 +2021,25 @@ struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
}
};

#if (FMT_USE_UTC_TIME)
template <typename Char, typename Duration>
struct formatter<std::chrono::time_point<std::chrono::utc_clock, Duration>,
Char> : formatter<std::tm, Char> {
FMT_CONSTEXPR formatter() {
basic_string_view<Char> default_specs =
detail::string_literal<Char, '%', 'F', ' ', '%', 'T'>{};
this->do_parse(default_specs.begin(), default_specs.end());
}

template <typename FormatContext>
auto format(std::chrono::time_point<std::chrono::utc_clock> val,
FormatContext& ctx) const -> decltype(ctx.out()) {
return formatter<std::tm, Char>::format(
localtime(std::chrono::utc_clock::to_sys(val)), ctx);
}
};
#endif

template <typename Char> struct formatter<std::tm, Char> {
private:
enum class spec {
Expand Down
9 changes: 9 additions & 0 deletions test/chrono-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -641,3 +641,12 @@ TEST(chrono_test, cpp20_duration_subsecond_support) {
}

#endif // FMT_STATIC_THOUSANDS_SEPARATOR

#if (FMT_USE_UTC_TIME)
TEST(chrono_test, utc_clock) {
auto t1 = std::chrono::system_clock::now();
auto t1_utc = std::chrono::utc_clock::from_sys(t1);
EXPECT_EQ(fmt::format("{:%Y-%m-%d %H:%M:%S}", t1),
fmt::format("{:%Y-%m-%d %H:%M:%S}", t1_utc));
}
#endif

0 comments on commit b512318

Please sign in to comment.