Skip to content

Commit

Permalink
Fix local time switch for StringToTime
Browse files Browse the repository at this point in the history
  • Loading branch information
sjanel committed Dec 21, 2024
1 parent 6fabc44 commit fea1440
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 22 deletions.
23 changes: 6 additions & 17 deletions src/schema/include/timepoint-schema.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ namespace cct::schema {
struct TimePoint {
auto operator<=>(const TimePoint &) const noexcept = default;

// 2023 - 01 - 01 T 12 : 34 : 56 Z
static constexpr size_t strLen() { return 4U + 1U + 2U + 1U + 2U + 1U + 2U + 1U + 2U + 1U + 2U + 1U; }

char *appendTo(char *buf) const { return std::ranges::copy(TimeToString(ts), buf).out; }

::cct::TimePoint ts{};
};

Expand Down Expand Up @@ -50,23 +55,7 @@ template <>
struct to<JSON, ::cct::schema::TimePoint> {
template <auto Opts, is_context Ctx, class B, class IX>
static void op(auto &&value, Ctx &&, B &&b, IX &&ix) {
auto timeStr = ::cct::TimeToString(value.ts);
auto valueLen = timeStr.size();
bool withQuotes = ::cct::details::JsonWithQuotes<Opts>(b, ix);
int64_t additionalSize = (withQuotes ? 2L : 0L) + static_cast<int64_t>(ix) + static_cast<int64_t>(valueLen) -
static_cast<int64_t>(b.size());
if (additionalSize > 0) {
b.append(additionalSize, ' ');
}

if (withQuotes) {
b[ix++] = '"';
}
std::ranges::copy(timeStr, b.data() + ix);
ix += valueLen;
if (withQuotes) {
b[ix++] = '"';
}
::cct::details::ToStrLikeJson<Opts>(value, b, ix);
}
};
} // namespace glz::detail
8 changes: 6 additions & 2 deletions src/tech/src/timestring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,12 @@ TimePoint StringToTime(std::string_view timeStr, const char* format) {
std::tm utc{};
std::istringstream ss{std::string(timeStr)};
ss >> std::get_time(&utc, format);
// TODO: fix issue of local time switch
return Clock::from_time_t(std::mktime(&utc));
if (ss.fail()) {
throw exception("Failed to parse time string {}", timeStr);
}
// Convert timestamp to epoch time assuming UTC
std::time_t timet = timegm(&utc);
return Clock::from_time_t(timet);
}

Nonce Nonce_TimeSinceEpochInMs(Duration delay) {
Expand Down
5 changes: 2 additions & 3 deletions src/tech/test/timestring_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ TEST(TimeStringTest, TimeToString) {
}

TEST(TimeStringTest, FromToString) {
// TODO: below lines should be uncommented
// std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
// EXPECT_STREQ(TimeToString(now).c_str(), TimeToString(StringToTime(TimeToString(now).c_str())).c_str());
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
EXPECT_EQ(TimeToString(now), TimeToString(StringToTime(TimeToString(now).c_str())));
}
} // namespace cct

0 comments on commit fea1440

Please sign in to comment.