10#include <fmt/format.h>
18 static inline std::string to_x509_time_string(
const std::tm& time)
22 return fmt::format(
"{:%Y%m%d%H%M%SZ}", time);
25 static inline std::string to_x509_time_string(
28 return to_x509_time_string(
32 static inline std::string to_x509_time_string(
33 const std::chrono::system_clock::time_point& time)
35 return to_x509_time_string(fmt::gmtime(time));
39 const std::string& time)
42 const char* ts = time.c_str();
44 auto accepted_formats = {
49 for (
const auto* afmt : accepted_formats)
53 auto* sres = strptime(ts, afmt, &t);
54 if (sres !=
nullptr && *sres ==
'\0')
57 r -= std::chrono::seconds(t.tm_gmtoff);
63 std::vector<std::pair<const char*, int>> more_formats = {
65 {
"%04u-%02u-%02u %02u:%02u:%f %d:%02u", 8},
66 {
"%04u-%02u-%02uT%02u:%02u:%f %d:%02u", 8},
67 {
"%04u-%02u-%02u %02u:%02u:%f %03d %02u", 8},
68 {
"%02u%02u%02u%02u%02u%f%03d%02u", 8},
69 {
"%04u%02u%02u%02u%02u%f%03d%02u", 8},
70 {
"%04u-%02u-%02uT%02u:%02u:%f", 6},
71 {
"%04u-%02u-%02u %02u:%02u:%f", 6}};
73 for (
auto [fmt, n] : more_formats)
84 int rs = sscanf(ts, fmt, &y, &m, &d, &h, &mn, &s, &oh, &om);
85 if (rs >= 1 && rs == n)
87 using namespace std::chrono;
88 if (strncmp(fmt,
"%02u", 4) == 0)
91 y += y >= 50 ? 1900 : 2000;
96 auto date = year_month_day(year(y), month(m), day(d));
99 !date.ok() || (rs >= 6 && (h > 24 || mn > 60 || s < 0.0)) ||
100 (rs >= 8 && (s > 60.0 || oh < -23 || oh > 23 || om > 60)))
109 t.tm_year =
static_cast<int>(y) - 1900;
110 t.tm_mon =
static_cast<int>(m) - 1;
111 t.tm_mday =
static_cast<int>(d);
114 t.tm_hour =
static_cast<int>(h);
115 t.tm_min =
static_cast<int>(mn);
116 t.tm_sec =
static_cast<int>(s);
119 auto tt = timegm(&t);
123 auto offset_secs = oh * 3600 +
124 (oh < 0 ? -
static_cast<int>(om) :
static_cast<int>(om)) * 60;
134 throw std::runtime_error(
135 fmt::format(
"'{}' does not match any accepted time format", time));
138 static inline std::string to_x509_time_string(
const std::string& time)
140 return to_x509_time_string(time_point_from_string(time));
Definition contiguous_set.h:13
std::chrono::time_point< SystemClock > time_point
Definition nonstd.h:231
static time_point from_time_t(std::time_t t) noexcept
Definition nonstd.h:244
static std::time_t to_time_t(const time_point &t) noexcept
Definition nonstd.h:239