| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- #pragma once
- #include <nlohmann/json.hpp>
- #include <chrono>
- #include <string>
- #include <ctime>
- namespace smartbotic::common {
- class TimeUtils {
- public:
- using Clock = std::chrono::system_clock;
- using TimePoint = Clock::time_point;
- using Duration = Clock::duration;
- // Get current timestamp in milliseconds
- static int64_t nowMs();
- /**
- * A document's stored timestamp, in milliseconds.
- *
- * The database names document metadata one fixed way - _created_at,
- * _updated_at - and writes it in nanoseconds. Reading it with a guessed
- * spelling silently yields zero, which every screen renders as "unknown";
- * that was true of credentials, users, sessions and node definitions at
- * once. The unit is checked rather than divided blindly, because a value
- * already in milliseconds divided again lands in 1970.
- */
- static int64_t documentStamp(const nlohmann::json& document, const char* key);
- // Get current timestamp in seconds
- static int64_t nowSec();
- // Get current timestamp as TimePoint
- static TimePoint now();
- // Convert milliseconds to TimePoint
- static TimePoint fromMs(int64_t ms);
- // Convert TimePoint to milliseconds
- static int64_t toMs(TimePoint tp);
- // Format timestamp as ISO 8601 string
- static std::string toIso8601(int64_t ms);
- static std::string toIso8601(TimePoint tp);
- // Parse ISO 8601 string to milliseconds
- static int64_t parseIso8601(const std::string& str);
- // Check if timestamp has expired
- static bool isExpired(int64_t expiryMs);
- static bool isExpired(TimePoint expiry);
- // Add duration to timestamp
- static int64_t addMs(int64_t timestampMs, int64_t durationMs);
- static int64_t addSec(int64_t timestampMs, int64_t durationSec);
- };
- // RAII timer for measuring durations
- class ScopedTimer {
- public:
- explicit ScopedTimer(const std::string& name = "");
- ~ScopedTimer();
- int64_t elapsedMs() const;
- void reset();
- private:
- std::string name_;
- TimeUtils::TimePoint start_;
- };
- } // namespace smartbotic::common
|