2011-10-26 38 views
5

任何人都知道如何從當前時間提升到本地系統獲得簡單的日期格式?現在提高簡單的人類可讀日期時間

boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time(); 
boost::posix_time::time_facet *facet = new boost::posix_time::time_facet("%d-%m-%Y %H:%M:%S"); 

我見過使用cout.imbue的例子,但我只想要一個簡單的字符串。

回答

6

你可以試試這個代碼:

void FormatDateTime(
    std::string const&    format, 
    boost::posix_time::ptime const& date_time, 
    std::string&     result) 
    { 
    boost::posix_time::time_facet * facet = 
     new boost::posix_time::time_facet(format.c_str()); 
    std::ostringstream stream; 
    stream.imbue(std::locale(stream.getloc(), facet)); 
    stream << date_time; 
    result = stream.str(); 
    } 

設置格式"%d-%m-%Y %H:%M:%S"或任何方面你想要的。

在當地時間,使用boost::posix_time::second_clock::local_time()作爲第二個參數(date_time)。

+0

這是不特定的本地計算機...我需要提高::了posix_time ::現在的ptime =的boost ::了posix_time :: second_clock :: LOCAL_TIME(); – Bluebaron

+0

其他一切都很好。 – Bluebaron

+0

不會創建新的方面並在每次調用此函數時灌注它會導致大量開銷? – rve

3

我知道這是爲時已晚,但對搜索和我一樣:

#include <boost/format.hpp> 

const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); 

const boost::wformat f = boost::wformat(L"%02d.%02d.%s %02d:%02d") 
       % now.date().year_month_day().dayas_number() 
       % now.date().year_month_day().month.as_number() 
       % now.date().year_month_day().year 
       % now.time_of_day().hours() 
       % now.time_of_day().minutes(); 

const std::wstring result = f.str(); // "21.06.2013 14:38" 
+0

它應該是day.as_number()。由於6個字符的限制而無法編輯。 –

+0

我測試了代碼,年份並不總是格式正確。有時候,這一年會包含一個逗號(2,017.01.11-16:18:01),有時候不會(2017.01.11-16:18:01)在Mac OS上測試過。這個std :: to_wstring(now.date()。year_month_day()。year)有幫助。 – MPeli

相關問題