如何使用Boost.Date_Time格式化而不使用前导零
How do you format with Boost.Date_Time without leading zeros?
如何格式化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在这里提供了一个很好的解释。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- Boost Regex用于格式化MAC地址字符串
- boost::p roperty_tree XML 漂亮的打印,格式化
- boost::格式化和自定义打印 STD 容器
- 如何从格式化字符串中获取 Boost::p osix_time::p time
- boost regex格式化程序,如何使用自定义函数
- Boost::使用字符数组格式化
- 是否可以使用Boost.使用预分配的缓冲区格式化
- 使用boost::karma格式化纬度/经度字符串
- boost.log std::异常格式化程序找不到运算符<< 自己的命名空间中的重载
- 使用boost program_options处理帮助消息,删除默认值或重新格式化帮助消息
- 如何使用Boost.Date_Time格式化而不使用前导零
- Boost ptime:如何以浏览器在http请求的header内发送的方式格式化数据