Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format date and time string in C++

Tags:

c++

datetime

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 

Is using sprintf the only way?

like image 779
Tae-Sung Shin Avatar asked Apr 23 '12 22:04

Tae-Sung Shin


People also ask

How do you format date and time?

On the Home tab, click the Dialog Box Launcher next to Number. You can also press CTRL+1 to open the Format Cells dialog box. In the Category box, click Date or Time, and then choose the number format that is closest in style to the one you want to create.

What does Strftime mean in C?

strftime() is a function in C which is used to format date and time. It comes under the header file time. h, which also contains a structure named struct tm which is used to hold the time and date.

What is date format C?

ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S. 18:25:34. %u. ISO 8601 weekday as number with Monday as 1 (1-7)


2 Answers

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.

like image 85
Jerry Coffin Avatar answered Oct 04 '22 06:10

Jerry Coffin


I'd try std::put_time. See the link here for information on how to use it. It supports full format strings and such.

like image 31
Kevin Anderson Avatar answered Oct 04 '22 08:10

Kevin Anderson