如何使用格式 dd/mm/yyyy 格式化日期时间对象?

47

我该如何使用Boost库以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

2个回答

81
如果你正在使用Boost.Date_Time,则需要使用IO facets来完成。为了获取boost::posix_time::ptime的正确facet typedefs(wtime_facettime_facet等),你需要包含boost/date_time/posix_time/posix_time_io.hpp。一旦这个步骤完成,代码就很简单了。你在想要输出的ostream上调用imbue,然后只需输出你的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文档中还有格式标志列表,以防您想要输出更华丽的内容。


1
请参考 http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags 获取格式标志。 - Bertrand Marron
4
@Jules cout将会拥有所有权。请参考http://rhubbarb.wordpress.com/2009/10/17/boost-datetime-locales-and-facets/。 - RedX
3
本地化管理所有权。因此,如果您保留了此本地化存储,则可以将其用于任何输出流,而不仅仅是cout。 - CashCow
2
有趣的旁注:当我尝试将格式化日期时间转换为std::wstring时,我几乎被搞疯了,因为我无法正确运行它。最后我意识到有一个boost::posix_time::wtime_facet可以使用。 - anhoppe
1
警告:不要将time_facet *facet = new time_facet("%d-%b-%Y %H:%M:%S");放在boost::shared_ptr中!!!否则你将会花费你的下一天来调试这个疯狂的崩溃。 - Andrew Hundt

1
使用{fmt}库,您可以按照以下方式以所需格式打印日期:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <fmt/time.h>

int main() {
  auto now = boost::posix_time::second_clock::local_time();
  fmt::print("{:%d-%b-%Y %H:%M:%S}\n", to_tm(now));
}

这种格式化工具正在C++20中提出标准化:P0645
或者您可以使用在C++11中引入的std::put_time
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iomanip>
#include <iostream>

int main() {
  boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
  auto tm = to_tm(now);
  std::cout << std::put_time(&tm, "%d-%b-%Y %H:%M:%S");
}

免责声明:本人是 {fmt} 的作者。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接