tags:

views:

1007

answers:

6
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

Thanks, Noah

P.S. It's really much easier in ruby!:

>> Time.now.to_i.to_s
=> "1245089994"
+9  A: 

Try 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.

Fred Larson
Fred,Thanks for the explanation and the link. I'm amazed at how fast the answers came in -- S.O. rocks!Noah
Noah
+2  A: 

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

anon
Neil,How would you get a string value using C localtime? It seems like printf() does an implicit conversion, but I need the return value.Thanks,Noah
Noah
Your original question asked how to get a date, but it turns out that what you really wanted was the number of seconds as a string. It helps to be precise.
anon
+1  A: 

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

#include "ctime"

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

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

nulldevice
nulldevice, I wasn't clear above, but I wanted a string representation of the epoch date (timestamp).
Noah
+1  A: 

the function "ctime()" will convert a time to a string. If you want to control the way its printed, use "strftime". However, strftime() takes an argument of "struct tm". Use "localtime()" to convert the time_t 32 bit integer to a struct tm.

Matthias Wandel
A: 

There are a myriad of ways in which you might want to format time (depending on the time zone, how you want to display it, etc.), so you can't simply implicitly convert a time_t to a string.

The C way is to use ctime or to use strftime plus either localtime or gmtime.

If you want a more C++-like way of performing the conversion, you can investigate the Boost.DateTime library.

Josh Kelley
Josh, I was typing too fast. Forgot the "std::string s" in there. --Noah
Noah
Updated. Thanks.
Josh Kelley
+1  A: 

The C++ way is to use stringstream.

The C way is to use snprintf() to format the number:

 char buf[16];
 snprintf(buf, 16, "%lu", time(NULL));
Reed Hedges