开发者

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 a开发者_开发问答n 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";
}


Try sprintf(string_variable, "%d", time) or std::string(itoa(time))?


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

In the end time_t is just an integer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜