简体   繁体   中英

Getting a unix timestamp as a string in C++

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.

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

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";
}

尝试sprintf(string_variable, "%d", time)std::string(itoa(time))吗?

http://www.codeguru.com/forum/showthread.php?t=231056

In the end time_t is just an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM