Следующая функция попытается разобрать заданную строку с использованием std::get_time(), пробуя std::vector различных форматов datetime, пока один не увенчается успехом.
Она будет считать разбор успешным только если вся строка была обработана. Обратите внимание, что это не означает, что весь шаблон был сопоставлен, а только то, что каждый символ строки был обработан данным шаблоном.
parse_time_point.cpp
#include <ctime>
#include <iomanip>
#include <sstream>
#include <vector>
/**
* Parses a string representing a date and time using a list of possible formats,
* and returns a time point representing that date and time in the system clock's time zone.
*
* @param time_str The string to parse.
* @param formats A vector of possible formats for the string.
* @return A time point representing the parsed date and time in the system clock's time zone.
* @throws DatetimeParseFailure if the string cannot be parsed using any of the provided formats.
*/
std::chrono::time_point<std::chrono::system_clock> ParseTimePoint(const std::string& time_str, const std::vector<std::string>& formats) {
for (const auto& format : formats) {
std::tm t = {};
std::istringstream ss(time_str);
ss >> std::get_time(&t, format.c_str());
// Успех только если вся строка была обработана
if (!ss.fail() && ss.eof()) {
std::time_t timet = timegm(&t);
return std::chrono::system_clock::from_time_t(timet);
}
}
throw DatetimeParseFailure("Failed to parse time string");
}Её можно использовать, например, с одним из следующих списков форматов:
formats.cpp
const std::vector<std::string> datetimeFormats = {
"%Y-%m-%d %H:%M:%S",
"%Y/%m/%d %H:%M:%S",
"%Y%m%d %H:%M:%S",
"%Y-%m-%dT%H:%M:%S",
"%Y/%m/%dT%H:%M:%S"
};или
formats.cpp
const std::vector<std::string> dateFormats = {
"%Y-%m-%d",
"%Y/%m/%d",
"%Y%m%d"
};
Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow