繁体   English   中英

在C ++中将unix时间戳记作为字符串获取

[英]Getting a unix timestamp as a string in C++

我使用函数time()来获取C ++中的时间戳,但是这样做之后,我需要将其转换为字符串。 我不能使用ctime,因为我需要时间戳本身(以10个字符的格式)。 麻烦的是,我不知道time_t变量采用什么形式,所以我不知道要从中转换什么。 cout可以处理它,因此它必须是一些描述性的字符串,但是我不知道是什么。

如果有人可以帮助我,我将不胜感激。

或者,您可以将ctime的输出提供给MySQL datetime字段并正确解释它吗? 出于理解的考虑,我仍然希望回答问题的第一部分,但这可以解决我的问题。

time_t是某种整数。 如果cout以您想要的方式处理它,则可以使用std::stringstream将其转换为字符串:

std::string timestr(time_t t) {
   std::stringstream strm;
   strm << t;
   return strm.str();
}

我有同样的问题。 我解决了如下问题:

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

最后, time_t只是一个整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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