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++ 中格式化日期和时间字符串


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01