Lesson 195 +10 XP

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_t stores a moment as a single number - great for calculations.
  • struct tm stores 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(&timestamp);

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(&timestamp) prints the date a timestamp represents.
  • asctime(&datetime) prints the date a tm structure represents.
time_t timestamp = time(NULL);
cout << ctime(&timestamp);

TL;DR

  • time(NULL) returns the current timestamp as time_t.
  • time_t is a number; struct tm is the human-readable parts.
  • tm_year counts years since 1900; tm_mon counts months from 0.
  • localtime() / gmtime() turn timestamps into tm structures.
  • ctime() and asctime() print dates quickly.