π 2011-Aug-02 ⬩ βοΈ Ashwin Nanjappa ⬩ π·οΈ cpp, date, time ⬩ π Archive
The easiest way to obtain the date and time string in C++ is to use time, localtime_s and asctime_s. The output string is of the formΒ Tue Aug 02 15:11:23 2011
.
Here is the self-explanatory code:
#include <ctime>
time_t curTime;
struct tm locTime;
const int TimeStrLen = 26;
char timeStr[ TimeStrLen ];
if ( ( -1 != time( &curTime ) ) // Seconds since 01-01-1970
0 == localtime_s( &locTime, &curTime ) ) // Convert to local time
&& ( 0 == asctime_s( timeStr, TimeStrLen, &locTime ) ) // Convert to string
&& (
)
{"Date-time is: " << timeStr;
cout <<
}else
{"Error calculating date-time!" << endl;
cerr << 1 );
exit( }