2009-06-15 41 views
22
time_t seconds; 
time(&seconds); 

cout << seconds << endl; 

这给了我一个时间戳。我怎样才能把这个时代的日期变成一个字符串?time_t的字符串表示形式?

std::string s = seconds; 

不起作用

回答

33

尝试std::stringstream

#include <string> 
#include <sstream> 

std::stringstream ss; 
ss << seconds; 
std::string ts = ss.str(); 

围绕上述技术的一个很好的包装是Boost的lexical_cast

#include <boost/lexical_cast.hpp> 
#include <string> 

std::string ts = boost::lexical_cast<std::string>(seconds); 

而对于这样的问题,我喜欢用香草萨特链接The String Formatters of Manor Farm的。

UPDATE:

用C++ 11,使用to_string()

1

标准C++没有自己的时间/日期功能 - 您需要使用C localtime及相关函数。

+6

你原来的问题问及如何得到一个日期,但事实证明,你真正想要的是秒数作为一个字符串。它有助于确保准确。 – 2009-06-15 18:27:59

20

,如果你想在一个可读的字符串的时候试试这个:

#include <ctime> 

std::time_t now = std::time(NULL); 
std::tm * ptm = std::localtime(&now); 
char buffer[32]; 
// Format: Mo, 15.06.2009 20:20:00 
std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); 

有关的strftime进一步参考()检查cppreference.com

+0

nulldevice,我上面不清楚,但我想要一个时代日期(时间戳)的字符串表示。 – g33kz0r 2009-06-15 18:25:32

1

功能“的ctime()”将转换一次到一个字符串。 如果你想控制它的打印方式,使用“strftime”。但是,strftime()需要一个“struct tm”的参数。使用“localtime()”将time_t 32位整数转换为struct tm。

0

您可能想要格式化时间(取决于时区,想要如何显示它等等),有很多种方法,因此您不能简单地将time_t隐式转换为字符串。

C方式是使用ctime或使用strftime加上localtimegmtime

如果您需要更类似C++的方式来执行转换,您可以调查Boost.DateTime库。

+0

已更新。谢谢。 – 2009-06-15 18:39:14

2

C++的方式是使用stringstream。

的C的方法是使用的snprintf()格式化数字:

char buf[16]; 
snprintf(buf, 16, "%lu", time(NULL)); 
+1

time_t不一定是无符号的或长度相同。实际上,它通常是经过签名的:http://stackoverflow.com/questions/471248/what-is-ultimately-a-time-t-typedef-to – nitzanms 2017-03-20 16:03:36

3

顶端回答这里不适合我的工作。

参见下面的实施例证明两者stringstream的和lexical_cast的答案的建议:

#include <iostream> 
#include <sstream> 

int main(int argc, char** argv){ 
const char *time_details = "2017-01-27 06:35:12"; 
    struct tm tm; 
    strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm); 
    time_t t = mktime(&tm); 
    std::stringstream stream; 
    stream << t; 
    std::cout << t << "/" << stream.str() << std::endl; 
} 

输出:1485498912分之1485498912 实测here


#include <boost/lexical_cast.hpp> 
#include <string> 

int main(){ 
    const char *time_details = "2017-01-27 06:35:12"; 
    struct tm tm; 
    strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm); 
    time_t t = mktime(&tm); 
    std::string ts = boost::lexical_cast<std::string>(t); 
    std::cout << t << "/" << ts << std::endl; 
    return 0; 
} 

输出:1485498912分之1485498912 实测:here


第二届收视率最高的解决方案本地工作:

#include <iostream> 
#include <string> 
#include <ctime> 

int main(){ 
    const char *time_details = "2017-01-27 06:35:12"; 
    struct tm tm; 
    strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm); 
    time_t t = mktime(&tm); 

    std::tm * ptm = std::localtime(&t); 
    char buffer[32]; 
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", ptm); 
    std::cout << t << "/" << buffer; 
} 

输出:1485498912/2017年1月27日6点35分十二秒 发现:here


相关问题