Loading lessons...
<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
| Type | What it holds |
|---|---|
time_t | a raw number of seconds since the "epoch", Jan 1, 1970 UTC |
struct tm | a human-friendly breakdown of year, month, day, hour, minute, second |
The struct tm splits a single instant into readable fields.
struct tm fields
| Field | Meaning | Notes |
|---|---|---|
tm_sec | seconds | 0 .. 60 (60 for a leap second) |
tm_min | minutes | 0 .. 59 |
tm_hour | hours | 0 .. 23 |
tm_mday | day of month | 1 .. 31 |
tm_mon | month | 0 .. 11 - January is 0! |
tm_year | years since 1900 | 2026 is stored as 126! |
tm_wday | day of week | 0 = Sunday .. 6 = Saturday |
tm_yday | day of year | 0 .. 365 |
tm_isdst | daylight saving | >0 in DST, 0 when not, <0 if unknown |
The functions
| Function | Signature | What it does |
|---|---|---|
time | time(&t) | current calendar time as time_t; NULL skips the pointer arg |
localtime | localtime(&t) | converts time_t to a struct tm in local time |
gmtime | gmtime(&t) | converts time_t to a struct tm in UTC time |
asctime | asctime(&tm) | struct tm to a fixed-format C-string |
ctime | ctime(&t) | time_t to a fixed string (calls asctime internally) |
difftime | difftime(t2, t1) | seconds between two time_t values (t2 - t1) |
mktime | mktime(&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:
| Code | Meaning |
|---|---|
%Y | 4-digit year |
%y | 2-digit year |
%m | month, 01-12 |
%d | day of month, 01-31 |
%H | 24-hour hour |
%M | minute, 00-59 |
%S | second, 00-59 |
%a | abbreviated weekday, "Sat" |
%A | full weekday, "Saturday" |
Notes
- Always add offsets to
tm_year(+1900) andtm_mon(+1) when you display them. localtimereturns local time (your timezone + DST);gmtimereturns UTC. Pick cleanly.asctime/ctimeare simple but fixed-format; usestrftimefor custom output.difftimereturns adoubleof seconds between twotime_tvalues.- The pointer from
localtimepoints to static storage - don't keep it long-term or a second call will overwrite your values.
TL;DR
time_tis raw seconds;struct tmis readable fields.timenow,localtime/gmtimeto break it down,mktimeto pack it back up.difftimemeasures a gap in seconds.strftimeproduces formatted text - remember+1900for the year and+1for the month.