Question

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);
Was it helpful?

Solution 2

I'm not at all convinced that this is the best way to do it, but it works:

#include <time.h>
#include <string>
#include <sstream>
#include <iostream>
int main() {
    time_t now = time(0);
    tm *ltm = localtime(&now);
    std::stringstream date;
    date << ltm->tm_mday
         << "/"
         << 1 + ltm->tm_mon
         << "/"
         << 1900 + ltm->tm_year
         << " "
         << 1 + ltm->tm_hour
         << ":"
         << 1 + ltm->tm_min
         << ":"
         << 1 + ltm->tm_sec;
    std::cout << date.str() << "\n";
}

The strftime() function will do most of this work for you, but building up the parts of the string using a stringstream may be more generally useful.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top