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.
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.
#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; }
tm StructureIf 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.
#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; }
tm struct:tm_year returns the number of years since 1900. You must add 1900 to get the correct current year.tm_mon returns the month from 0 to 11. You must add 1 to get standard 1-12 months.Which header file must be included to work with dates and times in C++?