How to format a datetime to string using boost?(如何使用boost将日期时间格式化为字符串?)
问题描述
我想使用 boost 将日期/时间格式化为字符串.
I want to format a date/time to a string using boost.
从当前日期/时间开始:
Starting with the current date/time:
ptime now = second_clock::universal_time();
并以包含此格式的日期/时间的 wstring 结尾:
and ending up with a wstring containing the date/time in this format:
%Y%m%d_%H%M%S
你能告诉我实现这一目标的代码吗?谢谢.
Can you show me the code to achieve this? Thanks.
推荐答案
无论如何,这是我为此编写的函数:
For whatever it is worth, here is the function that I wrote to do this:
#include "boost/date_time/posix_time/posix_time.hpp"
#include <iostream>
#include <sstream>
std::wstring FormatTime(boost::posix_time::ptime now)
{
using namespace boost::posix_time;
static std::locale loc(std::wcout.getloc(),
new wtime_facet(L"%Y%m%d_%H%M%S"));
std::basic_stringstream<wchar_t> wss;
wss.imbue(loc);
wss << now;
return wss.str();
}
int main() {
using namespace boost::posix_time;
ptime now = second_clock::universal_time();
std::wstring ws(FormatTime(now));
std::wcout << ws << std::endl;
sleep(2);
now = second_clock::universal_time();
ws = FormatTime(now);
std::wcout << ws << std::endl;
}
这个程序的输出是:
20111130_142732
20111130_142734
我发现这些链接很有用:
I found these links useful:
- 如何格式化日期时间对象格式为dd/mm/yyyy?
- http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.time_facet
- http://www.cplusplus.com/reference/iostream/stringstream/str/
这篇关于如何使用boost将日期时间格式化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用boost将日期时间格式化为字符串?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
