String representation of time_t?


Question

time_t seconds;
time(&seconds);

cout << seconds << endl;

This gives me a timestamp. How can I get that epoch date into a string?

std::string s = seconds;

does not work

1
28
6/22/2012 7:07:14 PM

Accepted Answer

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().

37
4/17/2014 3:33:26 AM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon