Learn C
#include "stdlib/time_lib.h"

Time & Date with time.h in C

#concept

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.

#how it works
1

Stamp with time()

time_t now = time(NULL); — seconds since 1970-01-01 UTC, the universal timestamp currency.

2

Explode with localtime

struct tm *t = localtime(&now); exposes tm_year (+1900!), tm_mon (0–11!), tm_mday — always adjust before printing.

3

Format with strftime

strftime(buf, n, "%Y-%m-%d %H:%M", t) renders human dates safely into bounded buffers.

4

Intervals with difftime/clock

difftime(end, start) subtracts stamps portably; clock()/CLOCKS_PER_SEC times CPU consumption for benchmarks.

#example
#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;
}
Output
2026-09-20
1time(NULL) stamps the current moment as seconds-since-epoch.
2localtime explodes it into fields — adding 1900 to years and 1 to months corrects the famous offsets.
3%02d zero-pads month and day, printing a proper ISO date.
#use cases
Log timestamps via strftime-formatted local time
Elapsed-time measurement with difftime around operations
CPU benchmarking with clock() (not wall timeouts)
Remembering +1900/+1 every time struct tm prints

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.