如何在 C++ 中格式化日期和时间字符串

2022-01-12 00:00:00 datetime c++ mfc

假设我有 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.

相关文章