2011-06-21 32 views
3

如何格式化boost :: posix_time :: ptime對象而不是用零填充數字?如何在不帶前導零的情況下使用Boost.Date_Time進行格式化?

例如,我想顯示6/7/2011 6:30:25 PM而不是06/07/2011 06:30:25 PM

在.NET中,格式字符串應該是「m/d/yyyy h:mm:ss tt」。

下面是一些代碼做了錯誤的方式,只是爲了獲得一個想法:

boost::gregorian::date baseDate(1970, 1, 1); 
boost::posix_time::ptime shiftDate(baseDate); 
boost::posix_time::time_facet *facet = new time_facet("%m/%d/%Y"); 
cout.imbue(locale(cout.getloc(), facet)); 
cout << shiftDate; 
delete facet; 

Output: 01/01/1970 

回答

3

據我所知,這個功能不是內置Boost.DateTime,但它是非常容易的編寫自己的格式功能,例如:

template<typename CharT, typename TraitsT> 
std::basic_ostream<CharT, TraitsT>& print_date(
    std::basic_ostream<CharT, TraitsT>& os, 
    boost::posix_time::ptime const& pt) 
{ 
    boost::gregorian::date const& d = pt.date(); 
    return os 
     << d.month().as_number() << '/' 
     << d.day().as_number() << '/' 
     << d.year(); 
} 

template<typename CharT, typename TraitsT> 
std::basic_ostream<CharT, TraitsT>& print_date_time(
    std::basic_ostream<CharT, TraitsT>& os, 
    boost::posix_time::ptime const& pt) 
{ 
    boost::gregorian::date const& d = pt.date(); 
    boost::posix_time::time_duration const& t = pt.time_of_day(); 
    CharT const orig_fill(os.fill('0')); 
    os 
     << d.month().as_number() << '/' 
     << d.day().as_number() << '/' 
     << d.year() << ' ' 
     << (t.hours() && t.hours() != 12 ? t.hours() % 12 : 12) << ':' 
     << std::setw(2) << t.minutes() << ':' 
     << std::setw(2) << t.seconds() << ' ' 
     << (t.hours()/12 ? 'P' : 'A') << 'M'; 
    os.fill(orig_fill); 
    return os; 
} 
+0

謝謝。不想這樣做,但它有效。 – Eric

2

我完全與其他部門的迴應同意:似乎沒有被格式化符,讓有個位數天的最月的日期。

通常,有一種使用格式化程序串的方法(幾乎與普通的strftime格式相同)。這些格式說明符看起來像,例如:"%b %d, %Y"

tgamblin提供了一個很好的解釋here

相關問題