Loading lessons...
Date and Time
Date and Time
The <ctime> library brings dates and times to C++: a single number for timestamps, a struct tm for readable components.
Grab the current timestamp
The time() function gives you the current date and time as one number:
#include <ctime>
using namespace std;
time_t timestamp = time(NULL); // seconds since Jan 1, 1970
Pass NULL to skip the pointer and just use the return value.
Timestamps vs structures
time_tstores a moment as a single number - great for calculations.struct tmstores the parts of a date - great for humans.
The tm members you will meet most:
tm_year- years since 1900.tm_mon- month from 0 to 11 (0 is January).tm_mday- day of the month.tm_hour- hour in 24-hour form (23 is 11pm).
Turn a timestamp into a readable date
localtime() converts a timestamp to a tm in your time zone. Dereference it into a copy so the value stays stable:
time_t timestamp = time(NULL);
struct tm datetime = *localtime(×tamp);
cout << datetime.tm_year + 1900 << "-"
<< datetime.tm_mon + 1 << "-"
<< datetime.tm_mday << "\n";
Remember the offsets: add 1900 to tm_year and 1 to tm_mon to get the numbers people expect.
Quick display helpers
ctime(×tamp)prints the date a timestamp represents.asctime(&datetime)prints the date atmstructure represents.
time_t timestamp = time(NULL);
cout << ctime(×tamp);
TL;DR
time(NULL)returns the current timestamp astime_t.time_tis a number;struct tmis the human-readable parts.tm_yearcounts years since 1900;tm_moncounts months from 0.localtime()/gmtime()turn timestamps intotmstructures.ctime()andasctime()print dates quickly.