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

问题描述:

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

如果有人可以帮助我,这将是非常感激,我完全难住。

或者,你可以提供ctime的输出到MySQL日期时间字段,并让它正确解释?为了理解的缘故,我仍然希望能回答我的问题的第一部分,但这会解决我的问题。

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

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

假设time_t是一个整数对于可移植性来说并不是一个好主意:“可移植程序不应直接使用此类型的值,而是始终依靠对标准库元素的调用来将它们转换为可移植类型。” http://www.cplusplus.com/reference/ctime/time_t/ – Chris 2013-05-30 02:16:02

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

在端time_t仅仅是一个整数。

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

+0

这允许过程时间戳将被打印,但它总是返回134515192.具体而言,我的代码是: 炭时间戳[10]; sprintf(时间戳,“%d”,时间); then later 查询+ =时间戳 查询是一个std :: string。 – wyatt 2010-05-08 23:19:16

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

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