简体   繁体   English

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

[英]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. 我使用函数time()来获取C ++中的时间戳,但是这样做之后,我需要将其转换为字符串。 I can't use ctime, as I need the timestamp itself (in its 10 character format). 我不能使用ctime,因为我需要时间戳本身(以10个字符的格式)。 Trouble is, I have no idea what form a time_t variable takes, so I don't know what I'm converting it from. 麻烦的是,我不知道time_t变量采用什么形式,所以我不知道要从中转换什么。 cout handles it, so it must be a string of some description, but I have no idea what. cout可以处理它,因此它必须是一些描述性的字符串,但是我不知道是什么。

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? 或者,您可以将ctime的输出提供给MySQL datetime字段并正确解释它吗? 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. time_t是某种整数。 If cout handles it in the way you want, you can use a std::stringstream to convert it to a string: 如果cout以您想要的方式处理它,则可以使用std::stringstream将其转换为字符串:

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 http://www.codeguru.com/forum/showthread.php?t=231056

In the end time_t is just an integer. 最后, time_t只是一个整数。

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

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