Skip to main content

C++: Convert ISO timestamp to chrono time point

You will need to include these headers:

#include <charconv>
#include <iomanip>
#include <format>
#include <sstream>
#include <date/date.h>

The date library comes from here: https://github.com/HowardHinnant/date but you can omit it if your OS has the latest stdc++ library and C++20 compiler.

And no, installing C++20 compiler does not mean that you will get the new C++20 features in std::chrono. You will need to install newer libstdc++, for example on Debian that would be:

sudo apt install libstdc++-14-dev

Convert chrono time point to ISO string #

std::string timePointToIso(const std::chrono::system_clock::time_point& tp) {
    std::stringstream ss;
    ss << date::format("%FT%TZ", date::floor<std::chrono::milliseconds>(tp));
    return ss.str();
}

Convert ISO string to chrono time point #

std::chrono::system_clock::time_point isoToTimePoint(const std::string_view& str) {
    std::istringstream ss{std::string{str}};
    std::chrono::system_clock::time_point tp;
    ss >> date::parse("%FT%TZ", tp);
    return tp;
}

Convert chrono time point to UNIX timestamp #

uint64_t timePointToUnix(const std::chrono::system_clock::time_point& tp) {
    const auto epoch = tp.time_since_epoch();
    return std::chrono::duration_cast<std::chrono::seconds>(epoch).count();
}

Convert UNIX timestamp to chrono time point #

std::chrono::system_clock::time_point unixToTimePoint(const uint64_t value) {
    return std::chrono::system_clock::time_point{std::chrono::seconds{value}};
}

Convert time point to local time string #

std::string timePointToLocalString(const std::chrono::system_clock::time_point& tp) {
    std::stringstream ss;

    const auto u = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
    std::time_t t = u.count();

    ss << std::put_time(std::localtime(&t), "%c");
    return ss.str();
}