Reputation: 1013
Is there any way to convert a time_t
to a std::string
with the format YYYY-MM-DD HH:MM:SS automatically while keeping the code portable?
Upvotes: 44
Views: 111441
Reputation: 490078
Use localtime
to convert the time_t
to a struct tm
. You can use strftime
to print the desired data from that.
#include <time.h>
...
char buff[20];
time_t now = time(NULL);
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));
Upvotes: 76
Reputation: 103
If you want to have a function that can be called at multiple points in your code you can try this. It is based on the top answer, which you really should mark as accepted btw...
#include <ctime>
#include <string>
std::string get_localtime() {
char buffer[80];
std::time_t now = std::time(nullptr);
std::strftime(buffer, 80, "%Y-%m-%d-%H:%M:%S", localtime(&now));
std::string result(buffer);
return result;
}
Hope this helps someone.
Upvotes: 0
Reputation: 20236
Your only real option off the top of my head is either to write your own routine, or use the ctime() function defined in POSIX.1/C90. ctime() is certainly worth looking into, but if your date is not in the right timezone already, you will run into issues.
EDIT: I didn't think about using localtime as mentioned by Jerry below. Converting it to a struct tm does give you more possibilities including what he mentions, and strptime().
Upvotes: 1