C time.h Library
C time.h Library
The time.h library in C provides functions and types for date and time operations. It is widely used for:
-
Measuring time
-
Generating timestamps
-
Creating delays
-
Random number seeding
📌 Key Types in time.h
| Type | Description |
|---|---|
time_t |
Represents calendar time (usually seconds since 1 Jan 1970) |
struct tm |
Represents broken-down time (year, month, day, hour, minute, second) |
clock_t |
Represents processor time used by a program |
📌 Common Functions
1️⃣ Current Time
| Function | Description |
|---|---|
time(time_t *t) |
Returns current time as time_t |
difftime(time_t end, time_t start) |
Returns difference in seconds |
clock() |
Returns processor time used by program |
Example:
2️⃣ Broken-down Time
| Function | Description |
|---|---|
localtime(const time_t *t) |
Converts time_t to local struct tm |
gmtime(const time_t *t) |
Converts time_t to UTC struct tm |
mktime(struct tm *tm) |
Converts struct tm back to time_t |
Example:
3️⃣ Formatting Time
| Function | Description |
|---|---|
asctime(const struct tm *tm) |
Converts struct tm to string |
ctime(const time_t *t) |
Converts time_t to string |
strftime(char *s, size_t max, const char *format, const struct tm *tm) |
Formats time into string |
Example:
4️⃣ Delays and Timing
| Function | Description |
|---|---|
clock() |
Measures CPU time used |
sleep(unsigned int seconds) |
Pauses program for seconds (unistd.h on Linux) |
difftime(time_t end, time_t start) |
Computes difference between times |
Example:
5️⃣ Seeding Random Numbers
📌 Summary Table
| Function | Purpose |
|---|---|
time |
Get current time as time_t |
localtime |
Convert time_t to local time (struct tm) |
gmtime |
Convert time_t to UTC time |
mktime |
Convert struct tm to time_t |
asctime |
Convert struct tm to string |
ctime |
Convert time_t to string |
strftime |
Format time as string |
clock |
Get CPU time used |
difftime |
Compute difference in seconds |
srand(time(NULL)) |
Seed random numbers |
✅ Notes
-
time_tis usually seconds since 1 Jan 1970 (Epoch). -
struct tmfields:-
tm_year: years since 1900 -
tm_mon: 0-11 -
tm_mday: 1-31 -
tm_hour,tm_min,tm_sec
-
-
Use
strftimefor custom date-time formats. -
Combine with
stdlib.hfor random number seeding.
