如何使用格式 dd/mm/yyyy 格式化日期时间对象? [英] How to format date time object with format dd/mm/yyyy?

查看:29
本文介绍了如何使用格式 dd/mm/yyyy 格式化日期时间对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Boost 库在格式 dd/mm/yyyy H?

How could I print the current date, using Boost libraries, in the format dd/mm/yyyy H?

我有什么:

boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
cout << boost::posix_time::to_simple_string(now).c_str();

2009-Dec-14 23:31:40

但我想要:

2009 年 12 月 14 日 23:31:40

14-Dec-2009 23:31:40

推荐答案

如果您使用的是 Boost.Date_Time,这是使用 IO facet 完成的.

If you're using Boost.Date_Time, this is done using IO facets.

您需要包含 boost/date_time/posix_time/posix_time_io.hpp 以获得正确的 facet 类型定义(wtime_facettime_facet 等.) 用于 boost::posix_time::ptime.完成后,代码非常简单.您在要输出到的 ostream 上调用 imbue,然后输出您的 ptime:

You need to include boost/date_time/posix_time/posix_time_io.hpp to get the correct facet typedefs (wtime_facet, time_facet, etc.) for boost::posix_time::ptime. Once this is done, the code is pretty simple. You call imbue on the ostream you want to output to, then just output your ptime:

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

using namespace boost::posix_time;
using namespace std;

int main(int argc, char **argv) {
  time_facet *facet = new time_facet("%d-%b-%Y %H:%M:%S");
  cout.imbue(locale(cout.getloc(), facet));
  cout << second_clock::local_time() << endl;
}

输出:

14-Dec-2009 16:13:14

另见格式列表标记在boost文档中,以防你想输出一些更有趣的东西.

See also the list of format flags in the boost docs, in case you want to output something fancier.

这篇关于如何使用格式 dd/mm/yyyy 格式化日期时间对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆