You can use the C++20 features std::chrono::parse
/ std::chrono::from_stream
and set the timepoint to be in milliseconds.
A modified example from my error report on MSVC on this subject which uses from_stream
:
#include <chrono>
#include <iostream>
#include <locale>
#include <sstream>
int main() {
std::setlocale(LC_ALL, "C");
std::istringstream stream("2022-09-25T10:07:41.123456Z");
std::chrono::sys_time<std::chrono::milliseconds> tTimePoint;
std::chrono::from_stream(stream, "%Y-%m-%dT%H:%M:%S%Z", tTimePoint);
std::cout << tTimePoint << '\n';
auto since_epoch = tTimePoint.time_since_epoch();
std::cout << since_epoch << '\n'; // 1664100461123ms
// or as 1664100461.123s
std::chrono::duration<double> fsince_epoch = since_epoch;
std::cout << std::fixed << std::setprecision(3) << fsince_epoch << '\n';
}
Demo
If you are stuck with C++11 - C++17 you can install the date
library by Howard Hinnant. It's the base of what got included in C++20 so if you upgrade to C++20 later, you will not have many issues.
#include "date/date.h"
#include <chrono>
#include <iostream>
#include <sstream>
int main() {
std::istringstream stream("2022-09-25T10:07:41.123456Z");
date::sys_time<std::chrono::milliseconds> tTimePoint;
date::from_stream(stream, "%Y-%m-%dT%H:%M:%S%Z", tTimePoint);
auto since_epoch = tTimePoint.time_since_epoch();
// GMT: Sunday 25 September 2022 10:07:41.123
std::cout << since_epoch.count() << '\n'; // prints 1664100461123
}