I use this little function to get a nicely formatted date and time:
#include <ctime> #include <string> #include <vector> std::string stringftime(const char* format = "%c", const struct tm* tm = NULL) { if (tm == NULL) { time_t t = std::time(NULL); tm = std::localtime(&t); } const size_t size = 256; std::vector<char> vtime(size); if (std::strftime(&vtime[0], size, format, tm) == 0) { vtime[0] = '\0'; } return &vtime[0]; }
Example of its use:
#include <iostream> int main (void) { std::cout << stringftime() << "\n"; std::cout << stringftime("Today is %A, %B %d.") << "\n"; std::cout << stringftime("The time is %I:%M %p.") << "\n"; }
Fri Sep 9 16:07:58 2016 Today is Friday, September 09. The time is 04:07 PM.
The format specifiers accepted are listed here: strftime.