How to get the current date and time in C++

A lot of programming tasks require the current date and time for processing. In C++, this can be done using the following two methods:

1. Using the time and ctime methods

The 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.

Syntax

See the function definition of the time method below:

svg viewer

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 dayday monthmonth yearyear hours:minutes:secondshours:minutes:seconds.

svg viewer

Code example

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 system
time_t now = time(0);
// convert now to string form
char* date_time = ctime(&now);
cout << "The current date and time is: " << date_time << endl;
}

2. Using the localtime and asctime methods

The 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:

Code example

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 system
time_t now = time(0);
// convert now to local time
struct tm *local_time = localtime(&now);
// convert local_time to string form
char* 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

Copyright ©2025 Educative, Inc. All rights reserved