2014-02-05 63 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

相關問題