Time & Date with time.h in C
time.h models time as seconds since the epoch: time(NULL) stamps now as time_t, difftime(a, b) subtracts safely into doubles, and localtime/gmtime explode stamps into struct tm fields (year since 1900! month 0–11!). strftime formats with %Y-%m-%d style codes, and mktime converts broken-down time back.
For intervals, clock() measures CPU time consumed (not wall time) — fine for benchmarks, wrong for timeouts. C11's timespec_get adds nanosecond wall stamps. The tm field offsets (years from 1900, months from 0) are the eternal gotcha — add 1900 and 1 when printing human dates.
Stamp with time()
time_t now = time(NULL); — seconds since 1970-01-01 UTC, the universal timestamp currency.
Explode with localtime
struct tm *t = localtime(&now); exposes tm_year (+1900!), tm_mon (0–11!), tm_mday — always adjust before printing.
Format with strftime
strftime(buf, n, "%Y-%m-%d %H:%M", t) renders human dates safely into bounded buffers.
Intervals with difftime/clock
difftime(end, start) subtracts stamps portably; clock()/CLOCKS_PER_SEC times CPU consumption for benchmarks.
#include <stdio.h>#include <time.h> int main(void) { time_t now = time(NULL); struct tm *t = localtime(&now); printf("%d-%02d-%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.