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?
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?
ctime()
produces strings in that format. It takes a pointer to atime_t
.There's also
asctime()
that takes a pointer to astruct tm
and does the same.MFC has
COleDateTime
which has a contructor that takestime_t
(or__time64_t
) and has aFormat
method.If you need to worry about formatting on different locales, don't forget to initialize the CRT with the current locale. This affects COleDateTime too.
See my blog post which ties in MSDN articles and other sources. http://gilesey.wordpress.com/2012/12/30/initailizing-mfccrt-for-consumption-of-regional-settings-internationalizationc
I'd try
std::put_time
. See the link here for information on how to use it. It supports full format strings and such.The C library includes
strftime
specifically for formatting dates/times. The format you're asking for seems to correspond to something like this: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::put_time
is new with C++11, but C++03 has atime_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.