Add string-to-string time conversion.

This commit is contained in:
tastytea 2020-07-05 11:38:11 +02:00
parent 8325da3624
commit fac9c60eb6
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
2 changed files with 36 additions and 1 deletions

View File

@ -16,16 +16,25 @@
#include "time.hpp"
#include <chrono>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>
#include <string_view>
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

View File

@ -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