In C, date and time functions are provided by the <time.h> standard library. Unlike modern languages that have "Date objects," C represents time using simple numeric types (like seconds since a specific date) or structures containing individual components like day, month, and year.
To work with time in C, you need to understand the two primary ways data is stored:
tm_year, tm_mon, and tm_mday.The time() function captures the current system time in seconds, which can then be converted into a readable format using ctime().
When you need to extract specific parts (like just the year or month), you use the localtime() function to convert time_t into a struct tm.
| Member | Meaning (Range) |
|---|---|
tm_year |
Years since 1900 (e.g., 2024 is 124). |
tm_mon |
Months since January (0 to 11). |
tm_mday |
Day of the month (1 to 31). |
tm_wday |
Days since Sunday (0 to 6). |
To print dates in a specific format (e.g., DD-MM-YYYY), the strftime() function is used. It works similarly to printf but for dates.
You can calculate how long a piece of code takes to run using the clock() function, which tracks processor cycles.
tm_year to get the actual calendar year.localtime() uses a static buffer. For thread-safe programs, use localtime_r().