user3264174
user3264174

Reputation: 167

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

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);

Upvotes: 1

Views: 18575

Answers (2)

Predelnik
Predelnik

Reputation: 5246

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);

Upvotes: 3

Keith Thompson
Keith Thompson

Reputation: 263657

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.

Upvotes: 1

Related Questions