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

2023-07-20C/C++开发问题
2

本文介绍了如何使用格式 dd/mm/yyyy 格式化日期时间对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何使用 Boost 库在格式 dd/mm/yyyy H?

How could I print the current date, using Boost libraries, in the format 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

14-Dec-2009 23:31:40

推荐答案

如果您使用的是 Boost.Date_Time,这是使用 IO facet 完成的.

If you're using Boost.Date_Time, this is done using IO facets.

您需要包含 boost/date_time/posix_time/posix_time_io.hpp 以获得正确的 facet 类型定义(wtime_facettime_facet 等.) 用于 boost::posix_time::ptime.完成后,代码非常简单.您在要输出到的 ostream 上调用 imbue,然后输出您的 ptime:

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:

#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文档中,以防你想输出一些更有趣的东西.

See also the list of format flags in the boost docs, in case you want to output something fancier.

这篇关于如何使用格式 dd/mm/yyyy 格式化日期时间对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6