Add string-to-string time conversion.
This commit is contained in:
parent
8325da3624
commit
fac9c60eb6
22
src/time.cpp
22
src/time.cpp
|
@ -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
|
||||
|
|
15
src/time.hpp
15
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
|
||||
|
|
Reference in New Issue