Getting the current time as a YYYY-MM-DD-HH-MM-SS string

ltjax picture ltjax · Mar 25, 2011 · Viewed 37.4k times · Source

I'm trying to get the current time as a "YYYY-MM-DD-HH-MM-SS" formatted string in an elegant way. I can take the current time in ISO format from Boost's "Date Time" library, but it has other delimiting strings which won't work for me (I'm using this in a filename). Of course I can just replace the delimiting strings, but have a feeling that there's a nicer way to do this with date-time's formatting options. Is there such a way, and if so, how can I use it?

Answer

Null Set picture Null Set · Mar 25, 2011

Use std::strftime, it is standard C++.

#include <cstdio>
#include <ctime>

int main ()
{
    std::time_t rawtime;
    std::tm* timeinfo;
    char buffer [80];

    std::time(&rawtime);
    timeinfo = std::localtime(&rawtime);

    std::strftime(buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo);
    std::puts(buffer);

    return 0;
}