如何使用Boost.Date_Time格式化而不使用前导零

How do you format with Boost.Date_Time without leading zeros?

本文关键字:格式化 Boost 何使用 Date Time      更新时间:2023-10-16

如何格式化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

据我所知,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;
}

我完全同意另一种回应:似乎没有一个格式化程序说明符用个位数给出日期。

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

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