Lesson 214 +5 XP

<ctime> Functions Reference

<ctime> Functions Reference

The <ctime> header works with wall-clock time. Dates, deltas, and formatting all flow through the struct tm and a raw time_t value.

The two basic types

TypeWhat it holds
time_ta raw number of seconds since the "epoch", Jan 1, 1970 UTC
struct tma human-friendly breakdown of year, month, day, hour, minute, second

The struct tm splits a single instant into readable fields.

struct tm fields

FieldMeaningNotes
tm_secseconds0 .. 60 (60 for a leap second)
tm_minminutes0 .. 59
tm_hourhours0 .. 23
tm_mdayday of month1 .. 31
tm_monmonth0 .. 11 - January is 0!
tm_yearyears since 19002026 is stored as 126!
tm_wdayday of week0 = Sunday .. 6 = Saturday
tm_ydayday of year0 .. 365
tm_isdstdaylight saving>0 in DST, 0 when not, <0 if unknown

The functions

FunctionSignatureWhat it does
timetime(&t)current calendar time as time_t; NULL skips the pointer arg
localtimelocaltime(&t)converts time_t to a struct tm in local time
gmtimegmtime(&t)converts time_t to a struct tm in UTC time
asctimeasctime(&tm)struct tm to a fixed-format C-string
ctimectime(&t)time_t to a fixed string (calls asctime internally)
difftimedifftime(t2, t1)seconds between two time_t values (t2 - t1)
mktimemktime(&tm)reverse: struct tm back to a time_t

The classic now-print dance

cpp
include <ctime>
include <iostream>

using namespace std;

int main() {
    time_t now = time(nullptr);
    tm* local = localtime(&now);

    cout << "Year is " << (local->tm_year + 1900) << '\n';
    cout << "Month is " << (local->tm_mon + 1) << '\n';  // 0-based!
    return 0;
}

The two fields - month and year - need the offsets corrected.

strftime - formatting like a pro

strftime(buf, size, format, &tm) writes a formatted string into a buffer:

char buffer[80];
strftime(buffer, 80, "%Y-%m-%d", &tm);   // "2026-08-09"

Common format codes:

CodeMeaning
%Y4-digit year
%y2-digit year
%mmonth, 01-12
%dday of month, 01-31
%H24-hour hour
%Mminute, 00-59
%Ssecond, 00-59
%aabbreviated weekday, "Sat"
%Afull weekday, "Saturday"

Notes

  • Always add offsets to tm_year (+1900) and tm_mon (+1) when you display them.
  • localtime returns local time (your timezone + DST); gmtime returns UTC. Pick cleanly.
  • asctime/ctime are simple but fixed-format; use strftime for custom output.
  • difftime returns a double of seconds between two time_t values.
  • The pointer from localtime points to static storage - don't keep it long-term or a second call will overwrite your values.

TL;DR

  • time_t is raw seconds; struct tm is readable fields.
  • time now, localtime/gmtime to break it down, mktime to pack it back up.
  • difftime measures a gap in seconds.
  • strftime produces formatted text - remember +1900 for the year and +1 for the month.