Getting a unix timestamp as a string in C++
Solution 1
time_t
is some kind of integer. If cout
handles it in the way you want, you can use a std::stringstream
to convert it to a string:
std::string timestr(time_t t) {
std::stringstream strm;
strm << t;
return strm.str();
}
Solution 2
I had the same problem. I solved it as follows:
char arcString [32];
std::string strTmp;
// add start-date/start-time
if (strftime (&(arcString [0]), 20, "%Y-%m-%d_%H-%M-%S", (const tm*) (gmtime ((const time_t*) &(sMeasDocName.sStartTime)))) != 0)
{
strTmp = (char*) &(arcString [0]);
}
else
{
strTmp = "1970-01-01_00:00:00";
}
Solution 3
Try sprintf(string_variable, "%d", time)
or std::string(itoa(time))
?
wyatt
Updated on November 19, 2022Comments
-
wyatt over 1 year
I'm using the function time() in order to get a timestamp in C++, but, after doing so, I need to convert it to a string. I can't use ctime, as I need the timestamp itself (in its 10 character format). Trouble is, I have no idea what form a time_t variable takes, so I don't know what I'm converting it from. cout handles it, so it must be a string of some description, but I have no idea what.
If anyone could help me with this it'd be much appreciated, I'm completely stumped.
Alternately, can you provide the output of ctime to a MySQL datetime field and have it interpreted correctly? I'd still appreciate an answer to the first part of my question for understanding's sake, but this would solve my problem.
-
wyatt almost 14 yearsThis allowed the process timestamp to be printed, but it always returns 134515192. specifically, my code is: char timestamp[10]; sprintf(timestamp, "%d", time); then later query += timestamp query being an std::string.
-
Chris almost 11 yearsAssuming time_t is an integer is not really a good idea in regards to portability: "Portable programs should not use values of this type directly, but always rely on calls to elements of the standard library to translate them to portable types." cplusplus.com/reference/ctime/time_t