21

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?

ltjax
  • 15,837
  • 3
  • 39
  • 62

2 Answers2

38

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;
}
Null Set
  • 5,374
  • 24
  • 37
  • 3
    Something that writes to a `std::string` and thus has no concerns about buffer overflows would be nice. Understandably, `strftime` would be expected to have a predictable maximum length. Are there any gotchas? – Craig McQueen Jan 07 '14 at 09:48
  • Is there any **thread-safe** solution? See [link](http://en.cppreference.com/w/cpp/chrono/c/localtime) - std::localtime() is not thread-safe. – Yuri Jan 11 '17 at 12:40
  • @Yuri use localtime_r() – CuteDoge Feb 01 '23 at 05:32
2

The answer depends on what you mean by get and take. If you are trying to output a formatted time string, use strftime(). If you are trying to parse a text string into a binary format, use strptime().

jbruni
  • 1,238
  • 8
  • 12