From 00d9b6660240ca960585dd66f215d9e883684f4b Mon Sep 17 00:00:00 2001 From: Marco van Dijk Date: Wed, 4 Jan 2023 11:34:24 +0100 Subject: [PATCH] Add UTC string parsing functions Change-Id: I51cbb2274e26811d28b303375ff75a32e272adcc --- lib/timing.cpp | 33 +++++++++++++++++++++++++++++++++ lib/timing.h | 2 ++ 2 files changed, 35 insertions(+) diff --git a/lib/timing.cpp b/lib/timing.cpp index a2d4396f..4cd99f12 100644 --- a/lib/timing.cpp +++ b/lib/timing.cpp @@ -6,6 +6,8 @@ #include #include //for gettimeofday #include //for time and nanosleep +#include +#include // emulate clock_gettime() for OSX compatibility #if defined(__APPLE__) || defined(__MACH__) @@ -122,6 +124,37 @@ std::string Util::getUTCStringMillis(uint64_t epoch_millis){ return std::string(result); } +// Returns the epoch of a UTC string in the format of %Y-%m-%dT%H:%M:%S%z +uint64_t Util::getMSFromUTCString(std::string UTCString){ + if (UTCString.size() < 24){return 0;} + // Strip milliseconds + std::string millis = UTCString.substr(UTCString.rfind('.') + 1, 3); + UTCString = UTCString.substr(0, UTCString.rfind('.')) + "Z"; + struct tm ptm; + memset(&ptm, 0, sizeof(struct tm)); + strptime(UTCString.c_str(), "%Y-%m-%dT%H:%M:%S%z", &ptm); + time_t ts = mktime(&ptm); + return ts * 1000 + atoll(millis.c_str()); +} + +// Converts epoch_millis into UTC time and returns the diff with UTCString in seconds +uint64_t Util::getUTCTimeDiff(std::string UTCString, uint64_t epochMillis){ + if (!epochMillis){return 0;} + if (UTCString.size() < 24){return 0;} + // Convert epoch to UTC time + time_t epochSeconds = epochMillis / 1000; + struct tm *ptmEpoch; + ptmEpoch = gmtime(&epochSeconds); + uint64_t epochTime = mktime(ptmEpoch); + // Parse UTC string and strip the milliseconds + UTCString = UTCString.substr(0, UTCString.rfind('.')) + "Z"; + struct tm ptmUTC; + memset(&ptmUTC, 0, sizeof(struct tm)); + strptime(UTCString.c_str(), "%Y-%m-%dT%H:%M:%S%z", &ptmUTC); + time_t UTCTime = mktime(&ptmUTC); + return epochTime - UTCTime; +} + std::string Util::getDateString(uint64_t epoch){ char buffer[80]; time_t rawtime = epoch; diff --git a/lib/timing.h b/lib/timing.h index c80e8a04..886950ae 100644 --- a/lib/timing.h +++ b/lib/timing.h @@ -18,5 +18,7 @@ namespace Util{ uint64_t epoch(); ///< Gets the amount of seconds since 01/01/1970. std::string getUTCString(uint64_t epoch = 0); std::string getUTCStringMillis(uint64_t epoch_millis = 0); + uint64_t getMSFromUTCString(std::string UTCString); + uint64_t getUTCTimeDiff(std::string UTCString, uint64_t epochMillis); std::string getDateString(uint64_t epoch = 0); }// namespace Util