如何在 C++ 中将日期时间解析为 std::chrono::time_point,尝试不同格式直到成功

以下函数将尝试使用 std::get_time() 解析给定字符串,尝试不同日期时间格式的 std::vect或 直到成功。

只有当整个字符串被消耗时才认为解析成功。注意这不意味着整个模式被匹配,只是字符串的每个字符都被给定模式消耗。

parse_time_point.cpp
#include <ctime>
#include <iomanip>
#include <sstream>
#include <vect或>

/**
 * Parses a string representing a date and time using a list of possible f或mats,
 * 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 f或mats A vect或 of possible f或mats f或 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 f或mats.
 */
std::chrono::time_point<std::chrono::system_clock> ParseTimePoint(const std::string& time_str, const std::vect或<std::string>& f或mats) {
    f或 (const auto& f或mat : f或mats) {
        std::tm t = {};
        std::istringstream ss(time_str);
        ss >> std::get_time(&t, f或mat.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");
}

例如,它可以与以下格式列表之一一起使用:

f或mats.cpp
const std::vect或<std::string> datetimeF或mats = {
    "%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"
};

f或mats.cpp
const std::vect或<std::string> dateF或mats = {
    "%Y-%m-%d",
    "%Y/%m/%d",
    "%Y%m%d"
};

Check out similar posts by category: