Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

date

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;
}
like image 566
Tina J Avatar asked Jul 10 '14 21:07

Tina J


2 Answers

This is a portable method using the C++11 chrono library:

#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>

// ...

std::string time_in_HH_MM_SS_MMM()
{
    using namespace std::chrono;

    // get current time
    auto now = system_clock::now();

    // get number of milliseconds for the current second
    // (remainder after division into seconds)
    auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;

    // convert to std::time_t in order to convert to std::tm (broken time)
    auto timer = system_clock::to_time_t(now);

    // convert to broken time
    std::tm bt = *std::localtime(&timer);

    std::ostringstream oss;

    oss << std::put_time(&bt, "%H:%M:%S"); // HH:MM:SS
    oss << '.' << std::setfill('0') << std::setw(3) << ms.count();

    return oss.str();
}
like image 129
Galik Avatar answered Sep 20 '22 20:09

Galik


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);
}
like image 29
Denis Sheremet Avatar answered Sep 19 '22 20:09

Denis Sheremet