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