c++ - 如何使用不带前导零的 Boost.Date_Time 进行格式化?

标签 c++ boost boost-date-time

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

例如,我想显示 6/7/2011 6:30:25 PM不是 06/07/2011 06:30:25私信

在 .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;
}

关于c++ - 如何使用不带前导零的 Boost.Date_Time 进行格式化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6431788/

相关文章:

c++ - 如何使用显存作为标准内存存储?

c++ - 我还需要多线程还是它已经过时了?

c++:如何在构造函数中初始化std::pair的成员

c++ - 提取日期字符串并确定哪个更早

头文件中的 C++ 静态原型(prototype)声明

c++ - 如何在从模板类继承时应用 move 语义

c++ - 如何使用 boost::date_time 从 time_t 获取本地日期时间?

c++ - 从周数和年份开始的月份

c++ - clang 代码补全 - 实现设计

c# - Boost 数学(ibeta_inv 函数)不是线程安全的?