How to format date and time string in C++(如何在 C++ 中格式化日期和时间字符串)
问题描述
假设我有 time_t 和 tm 结构.我不能使用 Boost 但 MFC.我怎样才能使它像下面这样的字符串?
Let's say I have time_t and tm structure. I can't use Boost but MFC. How can I make it a string like following?
Mon Apr 23 17:48:14 2012
使用 sprintf 是唯一的方法吗?
Is using sprintf the only way?
推荐答案
C 库包括 strftime 专门用于格式化日期/时间.您要求的格式似乎对应于以下内容:
The C library includes strftime specifically for formatting dates/times. The format you're asking for seems to correspond to something like this:
char buffer[256];
strftime(buffer, sizeof(buffer), "%a %b %d %H:%M:%S %Y", &your_tm);
我相信 std::put_time 使用类似的格式字符串,尽管它确实使您不必显式处理缓冲区.如果您想将输出写入流,这非常方便,但是要将其转换为字符串并没有多大帮助——您必须执行以下操作:
I believe std::put_time uses a similar format string, though it does relieve you of having to explicitly deal with a buffer. If you want to write the output to a stream, it's quite convenient, but to get it into a string it's not a lot of help -- you'd have to do something like:
std::stringstream buffer;
buffer << std::put_time(&your_tm, "%a %b %d %H:%M:%S %Y");
// now the result is in `buffer.str()`.
std::put_time 是 C++11 的新特性,但 C++03 在可以的语言环境中具有 time_put 方面做同样的事.如果没记错的话,我确实设法让它工作了一次,但在那之后觉得不值得那么麻烦,从那以后我就再也没有做过了.
std::put_time is new with C++11, but C++03 has a time_put facet in a locale that can do the same thing. If memory serves, I did manage to make it work once, but after that decided it wasn't worth the trouble, and I haven't done it since.
这篇关于如何在 C++ 中格式化日期和时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中格式化日期和时间字符串
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
