From fac9c60eb6eef429b8dea35b7422478e842717c4 Mon Sep 17 00:00:00 2001 From: tastytea Date: Sun, 5 Jul 2020 11:38:11 +0200 Subject: [PATCH] Add string-to-string time conversion. --- src/time.cpp | 22 +++++++++++++++++++++- src/time.hpp | 15 +++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/time.cpp b/src/time.cpp index 472d213..6da00a0 100644 --- a/src/time.cpp +++ b/src/time.cpp @@ -16,16 +16,25 @@ #include "time.hpp" +#include #include #include +#include +#include +#include #include namespace FediBlock::time { +using std::get_time; +using std::strftime; +using std::string; using std::string_view; +using std::stringstream; using std::time_t; using std::uint16_t; +using std::chrono::system_clock; string to_string(const system_clock::time_point &timepoint, const string_view format) @@ -35,9 +44,20 @@ string to_string(const system_clock::time_point &timepoint, std::tm *tm{nullptr}; tm = std::gmtime(&time); char buffer[bufsize]; - std::strftime(buffer, bufsize, format.data(), tm); + strftime(buffer, bufsize, format.data(), tm); return buffer; } +string to_string(const string_view timestring, const string_view format) +{ + std::tm tm{}; + tm.tm_isdst = -1; // Detect daylight saving time. + stringstream ss(timestring.data()); + ss >> get_time(&tm, + "%Y-%m-%dT%T"); // Assume time is UTC (%F doesn't work). + + return to_string(system_clock::from_time_t(timegm(&tm)), format); +} + } // namespace FediBlock::time diff --git a/src/time.hpp b/src/time.hpp index feebede..694f213 100644 --- a/src/time.hpp +++ b/src/time.hpp @@ -34,11 +34,26 @@ using std::chrono::system_clock; * @param timepoint The point in time to convert. * @param format Format of the string (optional, defaults to %FT%T). * + * See strftime(3) for information on how to construct a valid format string. + * * @since 0.2.0 */ [[nodiscard]] string to_string(const system_clock::time_point &timepoint, string_view format = "%FT%T"); +/*! + * @brief Return date and time as string. + + * @param timestring The time string to convert. Must be %FT%T. + * @param format Format of the string (optional, defaults to %FT%T). + * + * See strftime(3) for information on how to construct a valid format string. + * + * @since 0.2.0 + */ +[[nodiscard]] string to_string(string_view timestring, + string_view format = "%FT%T"); + } // namespace FediBlock::time #endif // FEDIBLOCK_BACKEND_TIME_HPP