C++ Date and Time

C++ Date and Time

C++ standard library does not provide a built-in "Date" type. However, it inherits the date and time functions from the C standard library.

To manipulate time and dates in C++, you must include the <ctime> header file.


1. Getting the Current Date and Time

The <ctime> header provides the time_t data type representing the system time (usually the number of seconds since January 1, 1970).

You can use the time() function to get the current system time, and the ctime() function to convert it into a readable human-format string.

Current Time Example

#include <iostream>
#include <ctime>
using namespace std;

int main() { // Declare a time_t variable to hold the time time_t now = time(0);

// Convert now to a string form using ctime() char* dt = ctime(&now);

cout << "The local date and time is: " << dt; return 0; }


2. Using the tm Structure

If you want to extract specific parts of a date, like the year, month, or day, it is better to convert the time into a tm structure.

The tm structure holds properties like tm_year, tm_mon, tm_mday, tm_hour, etc. We use the localtime() function to convert time_t into a tm struct.

Formatting Date Example

#include <iostream>
#include <ctime>
using namespace std;

int main() { time_t now = time(0);

// Convert time_t to a tm structure for local time tm *ltm = localtime(&now);

// Note: tm_year is years since 1900 cout << "Year: " << 1900 + ltm->tm_year << endl;

// Note: tm_mon is months since January (0-11) cout << "Month: " << 1 + ltm->tm_mon << endl;

cout << "Day: " << ltm->tm_mday << endl; cout << "Time: " << ltm->tm_hour << ":" << ltm->tm_min << ":" << ltm->tm_sec << endl;

return 0; }

Important Notes on the tm struct:


Exercise

?

Which header file must be included to work with dates and times in C++?