← GCC/C Index

🕐 <time.h> — Date & Time Functions

Provides types and functions to work with calendar time and CPU time. Key types: time_t (seconds since epoch) and struct tm (broken-down calendar time).

Include: #include <time.h> | Compile: gcc -Wall -o prog prog.c

📋 Functions & Macros

NamePrototype / ValueDescription
timetime_t time(time_t *t)Return current calendar time (Unix epoch)
clockclock_t clock(void)Return processor time used by program
difftimedouble difftime(time_t t2, time_t t1)Difference t2 - t1 in seconds
mktimetime_t mktime(struct tm *tm)Convert struct tm to time_t
gmtimestruct tm *gmtime(const time_t *t)Convert time_t to UTC struct tm
localtimestruct tm *localtime(const time_t *t)Convert time_t to local struct tm
asctimechar *asctime(const struct tm *tm)Convert struct tm to readable string
ctimechar *ctime(const time_t *t)Convert time_t to local time string
strftimesize_t strftime(char *s, size_t max, const char *fmt, const struct tm *tm)Format time into string

💡 Example Program

Copy, save as demo.c, and compile with the command shown at the bottom.

#include <stdio.h>
#include <time.h>

int main(void) {
    time_t now = time(NULL);
    struct tm *lt = localtime(&now);

    char buf[64];
    strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", lt);
    printf("Local time : %s\n", buf);

    const char *days[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
    printf("Day        : %s\n", days[lt->tm_wday]);

    clock_t start = clock();
    volatile long sum = 0;
    for (long i = 0; i < 100000000L; i++) sum += i;
    double elapsed = (double)(clock() - start) / CLOCKS_PER_SEC;
    printf("Loop took  : %.4f seconds\n", elapsed);
    return 0;
}
/* Compile: gcc -Wall -O2 -o time_demo time_demo.c */

← <ctype.h>  |  🏠 Index  |  <errno.h> →