The <time.h> header provides functions to manipulate date and time. It tracks time as a count of seconds since the Epoch (January 1, 1970).
Before using time functions, you must understand the two primary ways C stores time data:
| Type | Description |
|---|---|
time_t |
Stores the total seconds since the Epoch (usually a long integer). |
struct tm |
A structure holding components like year, month, day, hour, etc. |
clock_t |
Used for measuring processor time (CPU clock cycles). |
To get the current system time, we use the time() function. To convert it into a human-readable string, we use ctime().
When you need to access specific details like the "Day of the week" or "Month," you use localtime() to fill a tm struct.
tm_year: Years since 1900 (Add 1900 to get the current year).tm_mon: Months since January (0-11).tm_mday: Day of the month (1-31).tm_wday: Days since Sunday (0-6).If you want to know how long a specific piece of code takes to run, use clock().
For professional applications, strftime() allows you to format the date exactly how you want (e.g., "YYYY-MM-DD").
difftime(t1, t0): Returns the difference between two times in seconds.mktime(): Converts a tm struct back into a time_t value.gmtime(): Similar to localtime, but returns time in UTC/GMT.tm_year starts from 1900 and tm_mon starts from 0. Forgetting to add 1900 to the year is one of the most common bugs in C time programming!