String representation of time_t?

The top answer here does not work for me.

See the following examples demonstrating both the stringstream and lexical_cast answers as suggested:

#include <iostream>
#include <sstream>

int main(int argc, char** argv){
 const char *time_details = "2017-01-27 06:35:12";
  struct tm tm;
  strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
  time_t t = mktime(&tm); 
  std::stringstream stream;
  stream << t;
  std::cout << t << "/" << stream.str() << std::endl;
}

Output: 1485498912/1485498912 Found here


#include <boost/lexical_cast.hpp>
#include <string>

int main(){
    const char *time_details = "2017-01-27 06:35:12";
    struct tm tm;
    strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
    time_t t = mktime(&tm); 
    std::string ts = boost::lexical_cast<std::string>(t);
    std::cout << t << "/" << ts << std::endl;
    return 0;
}

Output: 1485498912/1485498912 Found: here


The 2nd highest rated solution works locally:

#include <iostream>
#include <string>
#include <ctime>

int main(){
  const char *time_details = "2017-01-27 06:35:12";
  struct tm tm;
  strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
  time_t t = mktime(&tm); 

  std::tm * ptm = std::localtime(&t);
  char buffer[32];
  std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", ptm);
  std::cout << t << "/" << buffer;
}

Output: 1485498912/2017-01-27 06:35:12 Found: here



Standard C++ does not have any time/date functions of its own - you need to use the C localtime and related functions.


Try std::stringstream.

#include <string>
#include <sstream>

std::stringstream ss;
ss << seconds;
std::string ts = ss.str();

A nice wrapper around the above technique is Boost's lexical_cast:

#include <boost/lexical_cast.hpp>
#include <string>

std::string ts = boost::lexical_cast<std::string>(seconds);

And for questions like this, I'm fond of linking The String Formatters of Manor Farm by Herb Sutter.

UPDATE:

With C++11, use to_string().


Try this if you want to have the time in a readable string:

#include <ctime>

std::time_t now = std::time(NULL);
std::tm * ptm = std::localtime(&now);
char buffer[32];
// Format: Mo, 15.06.2009 20:20:00
std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm);  

For further reference of strftime() check out cppreference.com

Tags:

C++

Timestamp