How to parse UTC date/timestamp in C++ to a std::chrono::time_point

The following function parses a string such as

2023-07-04 09:57:01

into a UTC timestamp.

#include <chrono>
#include <sstream>
#include <ctime>

std::chrono::time_point<std::chrono::system_clock> ParseDatetimeFromTimeString(const std::string& timeString) {
    std::tm t = {};
    std::istringstream ss(timeString);
    ss >> std::get_time(&t, "%Y-%m-%d %H:%M:%S");
    if (ss.fail()) {
        throw std::runtime_error("Failed to parse filename time string");
    }
    // Convert timestamp to epoch time assuming UTC
    std::time_t timet = timegm(&t);
    // Convert timet to std::chrono::time_point<std::chrono::system_clock>
    return std::chrono::system_clock::from_time_t(timet);
}

Test code

auto timepoint = ParseDatetimeFromTimeString("2023-07-04 09:57:01");
// print timepoint
std::time_t timet = std::chrono::system_clock::to_time_t(timepoint);
std::cout << std::put_time(std::gmtime(&timet), "%F %T") << std::endl; // Prints 2023-07-04 09:57:01

Since ParseDatetimeFromTimeString() parses the timestamp as UTC, we can use std::put_time(std::gmtime(...)) to print back the original timestamp:

2023-07-04 09:57:01