Format `time_point` to string with milliseconds

an anonymous user · April 30, 2022
#include <chrono>
#include <iostream>
#include <iomanip>
#include <sstream>

using Clock = std::chrono::high_resolution_clock;
static std::string timePointToString(const Clock::time_point &tp, const std::string &format, bool withMs = true, bool utc = true)
{
	const Clock::time_point::duration tt = tp.time_since_epoch();
	const time_t durS = std::chrono::duration_cast<std::chrono::seconds>(tt).count();
	std::ostringstream ss;
	if (const std::tm *tm = (utc ? std::gmtime(&durS) : std::localtime(&durS))) {
		ss << std::put_time(tm, format.c_str());
		if (withMs) {
			const long long durMs = std::chrono::duration_cast<std::chrono::milliseconds>(tt).count();
			ss << std::setw(3) << std::setfill('0') << int(durMs - durS * 1000);
		}
	}
	// gmtime/localtime() returned null
	else {
		ss << "<FORMAT ERROR>";
	}
	return ss.str();
}

int main() {
	const auto tp = Clock::now();
	std::cout << timePointToString(tp, "%Z %Y-%m-%d %H:%M:%S.") << std::endl;
    return 0;
}
Output
(Run the program to view its output)

Comments

Please sign up or log in to contribute to the discussion.