2014-02-05 64 views
0

请问可以将ltm->tm_mday转换为字符串吗?如何将time_t类型转换为C++中的字符串?

我试过这个,但是这不行!

time_t now = time(0); 
tm *ltm = localtime(&now); 
String dateAjoutSysteme = ltm->tm_mday + "/" + (1 + ltm->tm_mon) + "/" + (1900 + ltm->tm_year) + " " + (1 + ltm->tm_hour) + ":" + (1 + ltm->tm_min) + ":" + (1 + ltm->tm_sec); 
+0

查看'strftime()'。不知道是否有更多的C++ ish方法。 – TypeIA

+4

C++ 11:'std :: stringstream buf; buf << std :: put_time(ltm,“%d /%m /%I:%M:%S); std :: string date = buf.str()' – 0x499602D2

回答

1

我一点儿也不相信这是做到这一点的最好办法,但它的工作原理:

#include <time.h> 
#include <string> 
#include <sstream> 
#include <iostream> 
int main() { 
    time_t now = time(0); 
    tm *ltm = localtime(&now); 
    std::stringstream date; 
    date << ltm->tm_mday 
     << "/" 
     << 1 + ltm->tm_mon 
     << "/" 
     << 1900 + ltm->tm_year 
     << " " 
     << 1 + ltm->tm_hour 
     << ":" 
     << 1 + ltm->tm_min 
     << ":" 
     << 1 + ltm->tm_sec; 
    std::cout << date.str() << "\n"; 
} 

strftime()函数将完成大部分工作为你工作,但建立使用stringstream字符串的部分可能更通用。

+0

好吧,谢谢,那么,我怎么能'日期'转换为str ::字符串? – user3264174

+0

@ user3264174,看看答案。 – chris

+0

@ user3264174:'str()'方法从'std :: stringstream'返回一个'std :: string'。 –

1

您可以转换time_t或者使用复杂的strftime,无论是简单的asctime功能char数组,然后用相应的std::string构造。 简单的例子:

std::string time_string (std::asctime (timeinfo))); 

编辑:

专为您的代码,答案应该是:

std::time_t now = std::time(0); 
tm *ltm = std::localtime(&now); 
char mbstr[100]; 
std::strftime(mbstr, 100, "%d/%m/%Y %T", std::localtime(&t)); 
std::string dateAjoutSysteme (mbstr); 
+0

可以吗,请执行我的例子。 ,我不明白你说的是什么:/ – user3264174

+0

你的意思是'std :: asctime'而不是'asctime'? –

+0

@KeithThompson起初我想过简单的'asctime',但看起来像C++更好地写'std ::'one。 – Predelnik

相关问题