Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

datetime - How to format date and time string in C++

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

Is using sprintf the only way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...