A lot of programming tasks require the current date and time for processing. In C++, this can be done using the following two methods:
time
and ctime
methodsThe time
method returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, the function returns a value of -1.
See the function definition of the time
method below:
The
time_t
data type represents the system time and date as an integer.
The ctime
method returns a pointer to a string that holds the date and time in the form of
.
The code snippet (below) illustrates the usage of the two functions (above) to get the current date and time in C++:
#include <iostream>#include <ctime>using namespace std;int main(){// current date and time on the current systemtime_t now = time(0);// convert now to string formchar* date_time = ctime(&now);cout << "The current date and time is: " << date_time << endl;}
localtime
and asctime
methodsThe localtime
method converts a time_t
object representing calendar time to a tm
structure representing the corresponding time in the local time zone. It breaks down the calendar time into its components, such as year, month, day, hour, minute, etc., based on the local time zone. The syntax for the localtime
method is given below:
struct tm *localtime(const time_t *t_ptr);
The asctime
method converts a tm
structure representing calendar time to a C-style string (char*
) containing the textual representation of the time and date. It takes a pointer to a tm
structure as input and returns a pointer to a C-style string (char*
) containing the textual representation of the time and date. The syntax for the asctime
method is given below:
The code snippet (below) illustrates the usage of the two functions (above) to get the current date and time in C++:
#include <iostream>#include <ctime>using namespace std;int main(){// current date and time on the current systemtime_t now = time(0);// convert now to local timestruct tm *local_time = localtime(&now);// convert local_time to string formchar* date_time = asctime(local_time);cout << "The current date and time is: " << date_time << endl;}
While both pairs of methods (time
/ctime
and localtime
/asctime
) deal with time-related operations, they serve different purposes: time
/ctime
for obtaining and formatting the current time, and localtime
/asctime
for converting between time_t
and tm
representations and formatting the result as a string.
Free Resources