3

如何格式化 boost::posix_time::ptime 对象而不用零填充数字?

例如,我想显示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
4

2 回答 2

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;
}
于 2011-06-21T22:01:26.407 回答
2

我完全同意另一个回答:似乎没有一个格式化说明符可以给出一个数字的月份日期。

一般来说,有一种方法可以使用格式化程序字符串(几乎与常见strftime格式相同)。这些格式说明符看起来像,例如:"%b %d, %Y".

tgamblin在这里提供了一个很好的解释。

于 2012-02-22T18:39:37.557 回答