Skip to content

Instantly share code, notes, and snippets.

@polaris
Created June 20, 2016 11:53
Show Gist options
  • Save polaris/adee936198995a6f8c697c419d21f734 to your computer and use it in GitHub Desktop.
Save polaris/adee936198995a6f8c697c419d21f734 to your computer and use it in GitHub Desktop.
Convert a std::chrono::system_clock::time_point to std::string
static std::string timePointAsString(const std::chrono::system_clock::time_point& tp) {
std::time_t t = std::chrono::system_clock::to_time_t(tp);
std::string ts = std::ctime(&t);
ts.resize(ts.size()-1);
return ts;
}
@wvadhy
Copy link

wvadhy commented Aug 28, 2025

This works, but just to let you know this isn't thread-safe, std::ctime can return a nullptr if the static buffer it points to is overwritten by concurrent calls to the function, like logs for example which occur from varying sources.

An if predicate would be helpful here to prevent crashes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment