jeudi 3 mai 2018

c++11 chrono create a timestamp string with date, time and milliseconds formatted

So I have a function that I have made to generate timestamp strings in the form:

"YYYY-MM-DD HH:MM::SS.mmm". However it uses parts of the older std::time_t and std::strftime(), std::localtime() etc...

std::localtime gives a warning that it may be unsafe and to use std::localtime_s, however MSVS does not seem to have that function (or does it!?)... but anyway, what I want to do is try to use only the newer chrono libs.

Here is what I have so far:

std::string get_time_stamp()
{
    char buf[50] = {0};

    // Get the current time
    auto now = std::chrono::system_clock::now();
    // Format the date/time
    std::time_t now_tm_t = std::chrono::system_clock::to_time(now);
    std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now_tm_t);
    // Get the milliseconds
    int millis = std::chrono::time_point_cast<std::chrono::milliseconds>(now).time_since_epoch().count() % 100;
    // Note use snprintf for gcc
    sprintf_s(buf + strlen(buf), sizeof(buf) - strlen(buf), ".%03d", millis);
    return buf;
}

Can I make this cleaner and using only c++11 chrono (and perhaps not a char array) and avoid functions like strftime and localtime etc...? I find that std::chrono is a bit awkward to use - the simple stuff is simple, but it gets a bit mind-boggling after that...

Aucun commentaire:

Enregistrer un commentaire