marsh marsh - 1 month ago 17
C++ Question

Get current date down to milliseconds

I need to get the current UTC date in a printable format down to the milliseconds in c++11. I need this to run on Windows and Linux, so cross platform code is preferred. If this is impossible I can write two separate implementations.

This is what I have tried:

std::chrono::time_point<std::chrono::high_resolution_clock> time = std::chrono::system_clock::now();
std::time_t tt = std::chrono::high_resolution_clock::to_time_t(time);

struct tm* utc = nullptr;
gmtime_s(utc, &tt);

char buffer[256];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%dT-%H:%M:%S. %MILLESECONDS???, utc);


Though as you can see this does NOT get it down to the milliseconds. I can format the string myself if I need to as long as I can get a millisecond value somehow.

Answer

time_t contains seconds only, so you can use std::chrono functions for more precision:

#include <iostream>
#include <chrono>

int main() 
{
    typedef std::chrono::system_clock clock_type;

    auto now = clock_type::now();
    auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
    auto fraction = now - seconds;
    time_t cnow = clock_type::to_time_t(now);

    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
    std::cout << "Milliseconds: " << milliseconds.count() << '\n';
}
Comments