C time.h Header

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is time.h?

<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)
UsePrefer
Show a human date/timetime → localtime → strftime
Elapsed wall timedifftime
CPU time for a loopclock / CLOCKS_PER_SEC

How to Use time.h in C

Get a timestamp, break it down, then format—or measure a duration.

  1. Include <time.h> (and <stdio.h> to print).
  2. Call time(NULL) (or time(&t)) for the current time_t.
  3. Convert with localtime or gmtime; copy into your own struct tm.
  4. Format with strftime, or use difftime/clock for timing.
PieceRequired?Role
#include <time.h>YesTypes and time functions
time_tYes for calendar workEpoch seconds
struct tmFor displayYear, 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

Cheat Sheet

Core types, functions, and strftime tokens.

SymbolMeaning
time(NULL)Current epoch seconds
localtime / gmtimeLocal / UTC broken-down time
strftimeFormat struct tm into a string
difftime(t1, t0)t1 - t0 in seconds (double)
clock()CPU ticks; divide by CLOCKS_PER_SEC
%Y %m %dYear, month, day
%H %M %SHour (24h), minute, second
tm_year / tm_monYears since 1900 / month 0–11

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…

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

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(&current_time) == (time_t)(-1)) {
        fprintf(stderr, "time() failed\n");
        return 1;
    }

    time_copy = *localtime(&current_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;
}

How It Works

  1. Fetch epoch time. time(&current_time) stores seconds since 1970-01-01 UTC.
  2. Break down locally. localtime fills a static struct tm; we copy it into time_copy.
  3. Format. strftime writes year-month-day and 24-hour time into buffer.
  4. 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;
}

How It Works

  1. Mark start. time(NULL) records the first timestamp.
  2. Do work. The loop burns some wall time (exact amount depends on the machine).
  3. Mark end. Call time again after the loop.
  4. 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;
}

How It Works

  1. Capture ticks. clock() returns processor time used so far.
  2. Run the loop. Busy work increases CPU ticks.
  3. Subtract and scale. (end - start) / CLOCKS_PER_SEC → seconds of CPU time.
  4. 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.

Performance Notes

ApproachCostBest for
time / difftimeCheap; ~1s resolution oftenTimestamps, coarse elapsed time
localtime + strftimeSmall conversion + formatUser-facing date strings
clockFiner than time for CPUSimple 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.

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).

Next: wchar.h

Work with wide characters and wide time formatting.

wchar.h tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful