Get current time in milliseconds, or HH:MM:SS:MMM format

c++, date

Solution

This is a cleaner solution using HowardHinnant's date library.

std::string get_time()
{
    using namespace std::chrono;
    auto now = time_point_cast<milliseconds>(system_clock::now());
    return date::format("%T", now);
}

Problem

I've written a c++ function to get the current time in `HH:MM:SS` format. How can I add milliseconds or nanoseconds, so I can have a format like `HH:MM:SS:MMM`? If not possible, a function that returns current time in ms would also be good. I can then calculate the relative time distances between two log points myself. ``` string get_time() { time_t t = time(0); // get time now struct tm * now = localtime(&t); std::stringstream sstm; sstm << (now->tm_hour) << ':' << (now->tm_min) << ':' << now->tm_sec; string s = sstm.str(); return s; } ```

Original source