2009-06-15 210 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


相關問題