C++ provides functions in the <ctime> header to get and format the current date and time. By combining time(), localtime(), and asctime(), we can display the current local day, date, and time in a readable format.
- time() gets the current calendar time.
- localtime() converts it into the local date and time.
- asctime() converts the result into a human-readable format.
Approach
The program follows these steps to obtain and display the current local date and time:
- Call time() to get the current calendar time and store it in a time_t variable.
- Pass this value to localtime() to obtain the corresponding local date and time.
- Pass the resulting tm structure to asctime() and display the formatted output
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
// Declaring argument for time()
time_t tt;
// Declaring variable to store return value of
// localtime()
struct tm* ti;
// Applying time()
time(&tt);
// Using localtime()
ti = localtime(&tt);
cout << "Current Day, Date and Time is = "
<< asctime(ti);
return 0;
}
Output
Current Day, Date and Time is = Thu Sep 3 09:41:57 2026
Explanation
- time_t tt stores the current calendar time returned by time().
- time() gets the current time and stores it in tt.
- localtime() converts tt into the corresponding local date and time.
- asctime() converts the tm structure into a readable string, which is displayed using cout.
Note: The output depends on the system's current date, time, and time zone, as time() uses the system clock and localtime() uses the configured local time zone.