2017-06-19 78 views
0

我在尋找wstring的去到的方法來從一個std::time_t創建格式化(MySQL的DATETIME兼容即是)std::wstring。我目前做的是從std::stringstream創建std::put_time一個std::string,然後將其轉化爲std::wstring建設這樣的:創建的std ::帶日期

std::wstring foo(myStdString.begin(), myStdString.end())

但我覺得這是不是很優雅。有沒有一種既定的方式來做到這一點?一種使用寬字符的形式檢索一種方式可能?

答案(見下文)

我忘了在正確的格式指定格式字符串std::put_time,然後它的工作原理類似於std::string

這是我的最終代碼:

auto time_last_write = boost::filesystem::last_write_time(path); 
std::wostringstream wstream; 
wstream << std::put_time(std::gmtime(&time_last_write), L"%Y-%M-%d %H:%M:%S"); 
+0

爲什麼不使用'的std :: wostringstream'獲得'的std :: wstring'直接? –

+0

的std :: put_time似乎並沒有與它合作。 – DenverCoder21

+0

您可能需要明確指定字符類型,如'的std :: put_time (...)'。或者它可能是您在實現標準庫時的一個錯誤。你使用什麼編譯器?它是哪個版本? –

回答

2

您可以使用std::put_time()。請記住,字符類型不同於「格式化」的說法推斷:

#include <iostream> 
#include <iomanip> 
#include <ctime> 

int main() 
{ 
    std::time_t t = std::time(nullptr); 
    std::tm timestamp = *std::localtime(&t); 
    static const wchar_t *format = L"It is %T."; 
    std::wcout << std::put_time(&timestamp, format); 
} 

你可能會想寫入std::wostringstream而不是std::wcout,但原則是不變的。