diff --git a/SimoxUtility/algorithm/string/string_tools.cpp b/SimoxUtility/algorithm/string/string_tools.cpp index d58391f0a470fbb80b2191d517f70940413293bb..c5e9210b34fb0a3bd206366a452e7fb93c647e2b 100644 --- a/SimoxUtility/algorithm/string/string_tools.cpp +++ b/SimoxUtility/algorithm/string/string_tools.cpp @@ -176,6 +176,25 @@ bool alg::contains(const std::string& haystack, const std::string& needle) return boost::algorithm::contains(haystack, needle); } +time_t alg::to_time_t(const std::string &time, const std::string &time_format) +{ + std::tm tm = {}; + std::istringstream ss(time); + ss.imbue(std::locale()); + ss >> std::get_time(&tm, time_format.c_str()); + if (ss.fail()) + throw error::SimoxError("Failed converting string '" + time + "' to time with time format " + time_format); + else return mktime(&tm); +} + +std::string alg::to_string(time_t t, const std::string &time_format) +{ + char mbstr[100]; + std::strftime(mbstr, 100, time_format.c_str(), std::localtime(&t)); + return std::string(mbstr); +} + + unsigned long alg::count(const std::string& input, const std::string& search) { auto start = 0U; diff --git a/SimoxUtility/algorithm/string/string_tools.h b/SimoxUtility/algorithm/string/string_tools.h index 656b721fd58e52de34b1c3f18b02d4db4de941f0..1c36194e6c589f319c93da7fbd7a1c0542fcca43 100644 --- a/SimoxUtility/algorithm/string/string_tools.h +++ b/SimoxUtility/algorithm/string/string_tools.h @@ -144,4 +144,8 @@ namespace simox::alg { return multi_to_string(vector.begin(), vector.end()); } + + time_t to_time_t(const std::string &time, const std::string &time_format); + + std::string to_string(time_t t, const std::string &time_format); } diff --git a/SimoxUtility/tests/algorithm/string_tools.cpp b/SimoxUtility/tests/algorithm/string_tools.cpp index 4fc16a8a77ffb7e92116ed12bd9332fa32d6e39c..716e9925b99c87245ccaf4302b65b5f51c3eac25 100644 --- a/SimoxUtility/tests/algorithm/string_tools.cpp +++ b/SimoxUtility/tests/algorithm/string_tools.cpp @@ -102,6 +102,13 @@ BOOST_AUTO_TEST_CASE(capitalize_words) BOOST_CHECK_EQUAL_COLLECTIONS(out.begin(), out.end(), ex.begin(), ex.end()); } +BOOST_AUTO_TEST_CASE(time_conversion) +{ + std::string timeString = "2021-01-12"; + std::string timeFormat = "%Y-%m-%d"; + time_t time = simox::alg::to_time_t(timeString, timeFormat); + BOOST_CHECK_EQUAL(simox::alg::to_string(time, timeFormat), timeString); +} BOOST_AUTO_TEST_CASE(remove_prefix_suffix) {