<time.h> is the C standard header for calendar time and CPU time. time() returns seconds since the Unix epoch as time_t. Convert to fields with localtime or gmtime, format with strftime, and measure gaps with difftime or clock.
Remember
#include <time.h>
time_t now = time(NULL); // epoch seconds
struct tm t = *localtime(&now);
strftime(buf, size, "%Y-%m-%d %H:%M:%S", &t);
difftime(t1, t0) // wall seconds (double)
clock() / CLOCKS_PER_SEC // CPU seconds
tm_year = years since 1900
tm_mon = 0…11 (January = 0)
Use
Prefer
Show a human date/time
time → localtime → strftime
Elapsed wall time
difftime
CPU time for a loop
clock / CLOCKS_PER_SEC
Approach
How to Use time.h in C
Get a timestamp, break it down, then format—or measure a duration.
Include <time.h> (and <stdio.h> to print).
Call time(NULL) (or time(&t)) for the current time_t.
Convert with localtime or gmtime; copy into your own struct tm.
Format with strftime, or use difftime/clock for timing.
Piece
Required?
Role
#include <time.h>
Yes
Types and time functions
time_t
Yes for calendar work
Epoch seconds
struct tm
For display
Year, month, day, hour, …
Pseudocode
Pseudocode
now = time(NULL)
if now == -1: handle failure
tm = *localtime(&now) // or gmtime for UTC
// copy tm if you need the fields later
n = strftime(buf, sizeof(buf), format, &tm)
if n == 0: buffer too small
else: print buf
// elapsed wall time:
seconds = difftime(end, start)
// CPU time:
cpu = (clock_end - clock_start) / CLOCKS_PER_SEC
Reference
Cheat Sheet
Core types, functions, and strftime tokens.
Symbol
Meaning
time(NULL)
Current epoch seconds
localtime / gmtime
Local / UTC broken-down time
strftime
Format struct tm into a string
difftime(t1, t0)
t1 - t0 in seconds (double)
clock()
CPU ticks; divide by CLOCKS_PER_SEC
%Y %m %d
Year, month, day
%H %M %S
Hour (24h), minute, second
tm_year / tm_mon
Years since 1900 / month 0–11
Try it
Live Preview
Explore common time.h ideas: format a timestamp, compute a difference, or convert CPU ticks (browser simulation).
Simulates time → localtime → strftime and related patterns (same idea as the C examples below).
Result
Loading…
Trace
Worked Walkthrough — Format “Now”
Trace the usual pipeline from epoch seconds to a printable string.
Calculation
1. time(&now)
now = 1751721000, for example
2. localtime(&now)
tm_year = 126 → 1900 + 126 = 2026
tm_mon = 6 → July (0-based)
tm_mday = 5
tm_hour / tm_min / tm_sec → wall clock
3. Copy: time_copy = *localtime(&now)
4. strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &time_copy)
buf → "2026-07-05 16:30:00"
Check: strftime returns 0 if the buffer is too small
Code
C Examples
Compile with gcc file.c -std=c11 -o out. Printed times depend on when and where you run the program.
Example 1 — Current Date with strftime
Get the time, convert to local fields, and format a string.
C
#include <stdio.h>
#include <time.h>
int main(void) {
time_t current_time;
struct tm time_copy;
char buffer[80];
if (time(¤t_time) == (time_t)(-1)) {
fprintf(stderr, "time() failed\n");
return 1;
}
time_copy = *localtime(¤t_time);
if (strftime(buffer, sizeof(buffer),
"Current date and time: %Y-%m-%d %H:%M:%S",
&time_copy) == 0) {
fprintf(stderr, "strftime buffer too small\n");
return 1;
}
printf("%s\n", buffer);
printf("Epoch seconds: %lld\n", (long long)current_time);
return 0;
}
Output (example shape)
Current date and time: 2026-07-05 16:30:00
Epoch seconds: 1751721000
How It Works
Fetch epoch time.time(¤t_time) stores seconds since 1970-01-01 UTC.
Break down locally.localtime fills a static struct tm; we copy it into time_copy.
Format.strftime writes year-month-day and 24-hour time into buffer.
Check sizes. A return of 0 means the buffer was too small—grow it or shorten the format. Print with printf.
Example 2 — Elapsed Seconds with difftime
Measure wall-clock seconds between two time_t values.
C
#include <stdio.h>
#include <time.h>
int main(void) {
time_t start = time(NULL);
volatile unsigned long i;
time_t end;
for (i = 0; i < 300000000UL; i++) {
/* busy work */
}
end = time(NULL);
printf("Elapsed (whole seconds): %.0f\n", difftime(end, start));
return 0;
}
Output (varies by CPU)
Elapsed (whole seconds): 0 or 1
How It Works
Mark start.time(NULL) records the first timestamp.
Do work. The loop burns some wall time (exact amount depends on the machine).
Mark end. Call time again after the loop.
Subtract.difftime(end, start) returns seconds as double. Resolution is often one second—use clock for finer CPU timing.
Example 3 — CPU Time with clock
Measure processor time for a computation—not calendar waiting.
C
#include <stdio.h>
#include <time.h>
int main(void) {
clock_t start = clock();
volatile unsigned long i;
clock_t end;
double cpu_seconds;
for (i = 0; i < 50000000UL; i++) {
/* work */
}
end = clock();
cpu_seconds = (double)(end - start) / (double)CLOCKS_PER_SEC;
printf("CPU time used: %.4f seconds\n", cpu_seconds);
printf("CLOCKS_PER_SEC = %ld\n", (long)CLOCKS_PER_SEC);
return 0;
}
Output (varies by CPU)
CPU time used: 0.0523 seconds
CLOCKS_PER_SEC = 1000
How It Works
Capture ticks.clock() returns processor time used so far.
Run the loop. Busy work increases CPU ticks.
Subtract and scale.(end - start) / CLOCKS_PER_SEC → seconds of CPU time.
Know the difference. Sleeping or waiting on I/O may barely change clock, while difftime still advances.
Edge Cases & Pitfalls
These details catch most beginner time bugs.
static
Copy localtime / gmtime results
They return a pointer to shared storage. Use struct tm t = *localtime(&now); before the next call.
fields
tm_year and tm_mon offsets
tm_year is years since 1900; tm_mon is 0–11. January 2026 → year 126, month 0.
clock
clock ≠ wall clock
Use difftime for elapsed real time; use clock for CPU effort.
buffer
strftime needs space
If the buffer is too small, strftime returns 0. Check the return value.
Analysis
Performance Notes
Approach
Cost
Best for
time / difftime
Cheap; ~1s resolution often
Timestamps, coarse elapsed time
localtime + strftime
Small conversion + format
User-facing date strings
clock
Finer than time for CPU
Simple benchmarks
Do not call strftime in a tight hot loop unless you need the string. Cache formatted values when the clock second has not changed.
Remember
Key Takeaways
Pipeline:time → localtime/gmtime → strftime.
Copy: save struct tm before the next conversion call.
Timing:difftime = wall; clock = CPU.
Fields:tm_year since 1900; tm_mon is 0–11.
One line:time.h turns epoch seconds into calendar fields and back—and measures both wall and CPU time.
Frequently Asked Questions
time.h is the C standard header for calendar time and CPU time. It provides time() for epoch seconds, localtime/gmtime for broken-down fields, strftime for formatting, difftime for elapsed seconds, and clock() for processor time.
time_t is usually a scalar counting seconds since the Unix epoch (1970-01-01 UTC). struct tm holds human fields such as tm_year, tm_mon, tm_mday, tm_hour, tm_min, and tm_sec. Convert with localtime, gmtime, or mktime.
localtime converts a time_t to struct tm in the local timezone. gmtime converts to UTC. Use localtime for user-facing clocks; gmtime for logs in a universal reference.
clock returns an approximation of processor time used by the program, in ticks. Divide the difference by CLOCKS_PER_SEC to get CPU seconds. It is not wall-clock time—sleeping or waiting on I/O may barely advance clock.
strftime writes a formatted date/time string from a struct tm into your buffer. Common specifiers: %Y year, %m month, %d day, %H hour (24h), %M minute, %S second. It returns characters written (excluding null) or 0 if the buffer is too small.
Standard C localtime and gmtime return pointers to static storage—each call may overwrite the previous result. Copy into your own struct tm immediately, or use platform re-entrant versions like localtime_r (POSIX).