How to convert a time_t type to string in C++?

user3264174 picture user3264174 · Feb 5, 2014 · Viewed 12.1k times · Source

Is it possible to convert a ltm->tm_mday to string, please ?

I've tried this, but, this wouldn't work !

time_t now = time(0); 
tm *ltm = localtime(&now); 
String dateAjoutSysteme = ltm->tm_mday + "/" + (1 + ltm->tm_mon) + "/" + (1900 + ltm->tm_year) + " " + (1 + ltm->tm_hour) + ":" + (1 + ltm->tm_min) + ":" + (1 + ltm->tm_sec);

Answer

Predelnik picture Predelnik · Feb 5, 2014

You can convert time_t either using complex strftime, either simple asctime functions to char array and then use corresponding std::string constructor. Simple example:

std::string time_string (std::asctime (timeinfo)));

Edit:

Specifically for your code, the answer would be:

 std::time_t now = std::time(0);
 tm *ltm = std::localtime(&now); 
 char mbstr[100];
 std::strftime(mbstr, 100, "%d/%m/%Y %T", std::localtime(&t));
 std::string dateAjoutSysteme (mbstr);