Metalzero2
Metalzero2

Reputation: 551

How do I get system time in millisecond in C++ (not since epoch)?

I would like to get the current milliseconds of the system clock, in C++ (on Linux OS).

What I want is the hours, minutes, seconds and milliseconds of the system clock. I have been able to obtain the hours, minutes and seconds, with the following code:

chrono::system_clock::time_point currentTime = chono::system_clock::now();
time_t currentTime_c = chrono::system_clock::to_time_t(currentTime);
cout<<"Current time is: "<<put_time(localtime(&currentTime_c), "%T");

However, I have not been able to find how can I obtain the milliseconds of the system.

Just to clarify, I have seen people using chrono::duration to measure the milliseconds between time points in the software but this is not what I want. I want the milliseconds of the system clock.

Upvotes: 0

Views: 395

Answers (2)

eboakyegyau
eboakyegyau

Reputation: 225

You can try out this

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);

Upvotes: 0

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

Add a line:

auto msec = chrono::duration_cast<chrono::milliseconds>(currentTime - chrono::system_clock::from_time_t(currentTime_c));

Alternatively:

auto msec2 = chrono::duration_cast<chrono::milliseconds>(currentTime.time_since_epoch()) % 1000;

Upvotes: 3

Related Questions