我该如何使用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
boost::posix_time::ptime
的正确facet typedefs(wtime_facet
、time_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文档中还有格式标志列表,以防您想要输出更华丽的内容。
#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));
}
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");
}