diff --git a/include/ctools/cTools.h b/include/ctools/cTools.h index 54eebf5..11782ab 100644 --- a/include/ctools/cTools.h +++ b/include/ctools/cTools.h @@ -157,6 +157,16 @@ using namespace cocos2d; namespace ct // cTools { +///////////////////////////////////////////// +////// DATEs Conversions //////////////////// +///////////////////////////////////////////// + +// convert a string ISO8601 time to epoch time +bool iso8601ToEpoch(const std::string& vIsoDateTime, const std::string& vTimeFormat, std::time_t& vOutTime); + +// convert a epoch time to a string ISO8601 time +bool epochToISO8601(const std::time_t& vEpochTime, std::string& vOutTime); + ///////////////////////////////////////////// ////// UTF8 <> WideString /////////////////// ///////////////////////////////////////////// @@ -250,6 +260,9 @@ CTOOLS_API std::string toStr(const char* fmt, ...); CTOOLS_API std::string toUpper(const std::string& vStr, const std::locale& vLocale = std::locale()); CTOOLS_API std::string toLower(const std::string& vStr, const std::locale& vLocale = std::locale()); +// convert a string byte content to hex string +CTOOLS_API std::string toHex(const std::string& vStr); + template ::std::string toStrFromArray(T* arr, size_t n, char delimiter = ';') { if (arr) { diff --git a/src/cTools.cpp b/src/cTools.cpp index 55c2ab2..ec0ee34 100644 --- a/src/cTools.cpp +++ b/src/cTools.cpp @@ -49,6 +49,39 @@ SOFTWARE. #include #endif +bool ct::iso8601ToEpoch(const std::string& vIsoDateTime, const std::string& vTimeFormat, std::time_t& vOutTime) { + if (!vIsoDateTime.empty() && !vTimeFormat.empty()) { + struct std::tm time = {}; + std::istringstream ss(vIsoDateTime); + ss >> std::get_time(&time, vTimeFormat.c_str()); + if (ss.good()) { + time.tm_hour = 0; + time.tm_min = 0; + time.tm_sec = 0; +#ifdef _WIN32 + vOutTime = _mkgmtime(&time); +#else + vOutTime = timegm(&time); +#endif + return true; + } + } + return false; +} + +bool ct::epochToISO8601(const std::time_t& vEpochTime, std::string& vOutTime) { + auto tp = std::chrono::system_clock::from_time_t(vEpochTime); + auto tt = std::chrono::system_clock::to_time_t(tp); + auto* timeinfo = std::localtime(&tt); + std::ostringstream oss; + oss << std::put_time(timeinfo, "%Y-%m-%d"); + if (oss.good()) { + vOutTime = oss.str(); + return true; + } + return false; +} + std::string ct::UTF8Encode(const std::wstring& wstr) { std::string res; #if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER) @@ -127,6 +160,11 @@ ::std::string ct::toLower(const std::string& vStr, const std::locale& vLocale) { return str; } + std::string ct::toHex(const std::string& vStr) { + CTOOL_DEBUG_BREAK; + return {}; +} + ///////////////////////////////////////////////////////////// ///////// bitwize /////////////////////////////////////////// /////////////////////////////////////////////////////////////