C - time.h in C
1. What is time.h?
time.h is a C standard library header for dealing with date and time.
It provides:
-
Types for representing time values
-
Functions for getting the current time
-
Functions for converting, formatting, and manipulating time
2. Including the Header
#include <time.h>
3. Key Data Types in time.h
| Type | Purpose |
|---|---|
time_t |
Represents calendar time (seconds since the Epoch: 00:00:00 UTC, Jan 1, 1970) |
struct tm |
Holds a human-readable broken-down time (year, month, day, hour, etc.) |
clock_t |
Represents processor time used by a program (for performance measurement) |
4. Important Constants
| Constant | Meaning |
|---|---|
CLOCKS_PER_SEC |
Number of clock_t ticks per second (for converting processor time) |
5. Key Functions in time.h
5.1 Getting the Current Time
time_t t;
time(&t); // store current time in t
printf("%ld\n", t); // seconds since Epoch
Shortcut:
time_t t = time(NULL); // directly returns current time
5.2 Converting to Readable Time
time_t t = time(NULL);
char *str = ctime(&t); // converts to human-readable string
printf("Now: %s", str);
Example output:
Now: Thu Aug 14 10:20:30 2025
5.3 Broken-down Time (struct tm)
You can break a time_t into components:
struct tm *tm_info = localtime(&t);
printf("%d-%02d-%02d %02d:%02d:%02d\n",
tm_info->tm_year + 1900, // years since 1900
tm_info->tm_mon + 1, // months since Jan (0–11)
tm_info->tm_mday,
tm_info->tm_hour,
tm_info->tm_min,
tm_info->tm_sec);
5.4 Coordinated Universal Time (UTC)
struct tm *tm_utc = gmtime(&t);
Similar to localtime but gives UTC instead of local time.
5.5 Formatting Time (strftime)
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_info);
printf("Formatted time: %s\n", buffer);
Some common format specifiers:
-
%Y→ year (e.g., 2025) -
%m→ month (01–12) -
%d→ day of month -
%H→ hour (00–23) -
%M→ minute -
%S→ second -
%A→ weekday name -
%B→ month name
5.6 Parsing Time Back (mktime)
Converts a struct tm to time_t:
time_t t2 = mktime(tm_info);
Useful for doing date arithmetic.
5.7 Measuring Elapsed Time
clock_t start = clock();
// some code here
clock_t end = clock();
double cpu_time = (double)(end - start) / CLOCKS_PER_SEC;
printf("Time taken: %.5f seconds\n", cpu_time);
6. Summary Table of Common time.h Functions
| Function | Purpose |
|---|---|
time |
Get current calendar time |
ctime |
Convert time_t to string |
localtime |
Convert time_t to local broken-down time |
gmtime |
Convert time_t to UTC broken-down time |
strftime |
Format struct tm as a string |
mktime |
Convert struct tm to time_t |
difftime |
Compute difference between two times |
clock |
CPU time used by program |