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

标签 c++ boost date

如何打印当前日期,使用 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

但我想要:

14-Dec-2009 23:31:40

最佳答案

如果您使用 Boost.Date_Time ,这是使用 IO 方面完成的。

您需要包含 boost/date_time/posix_time/posix_time_io.hpp 以获得正确的 facet typedef(wtime_facettime_facet 等。 ) 用于 boost::posix_time::ptime。完成后,代码非常简单。您在要输出到的 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

另见list of format flags在 boost 文档中,以防你想输出一些更漂亮的东西。

关于c++ - 如何使用格式 dd/mm/yyyy 格式化日期时间对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1904317/

相关文章:

php - 当前日期减去 4 个月?

c++ - 使用 std::enable_if 重载函数以避免模板替换错误

c++ - c++中...的用途是什么

mysql - 同一张表的记录之间的日期差异

java - Intent 崩溃。安卓工作室

c++ - 错误 C2061 : syntax error : identifier 'buffer' when compiling algparam. h

c++ - 移植Qt4到Qt5 : unresolved external symbols

c++ - CMake 和绝对标题路径

c++ - 如何要求 boost::normal_distribution 在没有 for 循环的情况下生成大量随机变量 vector

c++ - boost mpz_int 基数不是 2、8、10、16