Skip to content

Instantly share code, notes, and snippets.

@bschlinker
Created February 5, 2018 18:32
Show Gist options
  • Save bschlinker/844a88c09dcf7a61f6a8df1e52af7730 to your computer and use it in GitHub Desktop.
Save bschlinker/844a88c09dcf7a61f6a8df1e52af7730 to your computer and use it in GitHub Desktop.
Timestamp with milliseconds
#include <chrono>
#include <iomanip>
#include <iostream>
string getTimestamp() {
// get a precise timestamp as a string
const auto now = std::chrono::system_clock::now();
const auto nowAsTimeT = std::chrono::system_clock::to_time_t(now);
const auto nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) % 1000;
std::stringstream nowSs;
nowSs
<< std::put_time(std::localtime(&nowAsTimeT), "%a %b %d %Y %T")
<< '.' << std::setfill('0') << std::setw(3) << nowMs.count();
return nowSs.str();
}
@vladimir-kuznetsov-epam

Hi, need to mention that std::localtime() is not a thread-safe.

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