C++ 如何使用格式 dd/mm/yyyy 格式化日期时间对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1904317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format date time object with format dd/mm/yyyy?
提问by Alfredo
How could I print the current date, using Boostlibraries, in the format dd/mm/yyyy H?
如何使用Boost库以 dd/mm/yyyy H 格式打印当前日期?
What I have:
我拥有的:
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
But I want:
但我想要:
14-Dec-2009 23:31:40
2009 年 12 月 14 日 23:31:40
回答by Todd Gamblin
If you're using Boost.Date_Time, this is done using IO facets.
如果您使用的是Boost.Date_Time,这是使用 IO facet 完成的。
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
:
您需要包括boost/date_time/posix_time/posix_time_io.hpp
以获得正确的面类型定义(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;
}
Output:
输出:
14-Dec-2009 16:13:14
See also the list of format flagsin the boost docs, in case you want to output something fancier.
另请参阅boost 文档中的格式标志列表,以防您想输出更高级的内容。
回答by vitaut
With the {fmt} libraryyou can print the date in the required format as follows:
使用{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));
}
This formatting facility is being proposed for standardization in C++20: P0645.
这个格式化工具被提议用于 C++20 的标准化:P0645。
Alternatively you can use std::put_time
which was introduced in C++11:
或者,您可以使用std::put_time
C++11 中引入的:
#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");
}
Disclaimer: I'm the author of {fmt}.
免责声明:我是 {fmt} 的作者。