Wie man Datetime in C++ in std::chrono::time_point parst, wobei verschiedene Formate ausprobiert werden bis Erfolg
Die folgende Funktion versucht, eine gegebene Zeichenkette mit std::get_time() zu parsen, wobei ein std::vector verschiedener Datetime-Formate ausprobiert wird, bis eines erfolgreich ist.
Sie betrachtet das Parsen nur dann als erfolgreich, wenn die gesamte Zeichenkette verbraucht wurde. Beachten Sie, dass dies nicht bedeutet, dass das gesamte Muster übereingestimmt hat, sondern nur, dass jedes Zeichen der Zeichenkette durch das gegebene Muster verbraucht wurde.
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());
// Only succeed if the entire string was consumed
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");
}Es kann beispielsweise mit einer der folgenden Formatlisten verwendet werden:
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"
};oder
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