c++ print time code example

Example 1: how to get current time in c++

//Simplest way to add time using ctime
	#include <ctime>

	time_t tt;
    time( &tt );
    tm TM = *localtime( &tt );

	//Must add 1 to month and 1900 to the year
    int month=TM.tm_mon+1;
    int day=TM.tm_mday;
    int year=TM.tm_year+1900;

Example 2: c++ print current time

// Current date/time based on current system
time_t now = time(0);

// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout << "The local date and time is: " << asctime(localtm) << endl;

// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}

Tags:

Cpp Example