C Date and Time
C Date and Time
In C programming, working with date and time is done using functions defined in the <time.h> library.
This library allows you to:
-
Get the current date and time
-
Format date/time
-
Measure execution time
-
Convert between time formats
📌 Common Data Type Used: time_t
time_t stores calendar time in seconds since January 1, 1970 (Unix Epoch).
1️⃣ Get Current Date and Time
Output (example):
2️⃣ Using localtime() to Break Down Time
You can extract year, month, day, time components using struct tm.
3️⃣ Formatting Time Using strftime()
Output:
4️⃣ Calculating Time Differences
You can measure how long something takes using difftime().
5️⃣ Converting struct tm Back to time_t
📌 Summary Table
| Function | Purpose |
|---|---|
time() |
Returns current time in seconds |
ctime() |
Converts time to readable string |
localtime() |
Converts time_t to structured time |
strftime() |
Formats date/time into a custom string |
difftime() |
Calculates time difference |
mktime() |
Converts structured time back to time_t |
