Code Yarns β€πŸ‘¨β€πŸ’»
Tech Blog ❖ Personal Blog

C++: Print Current Date and Time

πŸ“… 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
    )
{
    cout << "Date-time is: " << timeStr;
}
else
{
    cerr << "Error calculating date-time!" << endl;
    exit( 1 );
}