C time.h Library Reference
Complete reference for time.h - getting time, formatting dates, measuring durations, and working with timestamps.
What You Will Learn
- ✓Get current date and time
- ✓Format dates and times
- ✓Calculate time differences
- ✓Measure program execution time
01Introduction to time.h
⏰ What is time.h?
The <time.h> header provides functions for working with dates, times, and measuring durations in C. It's essential for logging, timestamps, scheduling, and performance measurement.
📋 Function Prototypes Reference
| Function | Prototype | Description |
|---|---|---|
| time() | time_t time(time_t *timer) | Get current calendar time |
| localtime() | struct tm *localtime(const time_t *timer) | Convert to local time |
| gmtime() | struct tm *gmtime(const time_t *timer) | Convert to UTC time |
| ctime() | char *ctime(const time_t *timer) | time_t → string |
| asctime() | char *asctime(const struct tm *tm) | struct tm → string |
| strftime() | size_t strftime(char *s, size_t max, const char *fmt, const struct tm *tm) | Custom format string |
| difftime() | double difftime(time_t end, time_t start) | Difference in seconds |
| mktime() | time_t mktime(struct tm *tm) | struct tm → time_t |
| clock() | clock_t clock(void) | CPU clock ticks |
1#include <stdio.h>2#include <time.h> // Include for time functions34int main() {5 // Get current time6 time_t now = time(NULL);7 printf("Current time: %s", ctime(&now));8 return 0;9}02Key Types: time_t and struct tm
time_t
A numeric type (usually long) representing seconds since January 1, 1970 (Unix Epoch).
time_t now = time(NULL);
struct tm
A structure with broken-down time components (year, month, day, hour, etc.).
struct tm *local;
local = localtime(&now);
📦 struct tm Members
tm_secSeconds (0-60)
tm_minMinutes (0-59)
tm_hourHours (0-23)
tm_mdayDay of month (1-31)
tm_monMonth (0-11)
tm_yearYears since 1900
tm_wdayDay of week (0=Sun)
tm_ydayDay of year (0-365)
tm_isdstDaylight saving flag
⚠️ Important Notes
- •
tm_monis 0-based: January = 0, December = 11 - •
tm_yearis years since 1900: 2024 = 124
03time() - Get Current Time
time() - Get Current Calendar Time
Returns seconds since January 1, 1970 00:00:00 UTC (Unix Epoch). If timer is not NULL, the result is also stored in *timer.
1#include <stdio.h>2#include <time.h>34int main() {5 // Method 1: Pass NULL, use return value6 time_t now = time(NULL);7 printf("Seconds since Jan 1, 1970: %ld\n", now);8 9 // Method 2: Pass pointer to store result10 time_t current;11 time(¤t);12 printf("Same value: %ld\n", current);13 14 return 0;15}Seconds since Jan 1, 1970: 1734278400
Same value: 1734278400
04localtime() and gmtime()
localtime() - Convert to Local Time
gmtime() - Convert to UTC Time
1#include <stdio.h>2#include <time.h>34int main() {5 time_t now = time(NULL);6 7 // Convert to local time8 struct tm *local = localtime(&now);9 printf("Local Time:\n");10 printf(" Date: %d-%02d-%02d\n", 11 local->tm_year + 1900, // Add 1900 to get actual year12 local->tm_mon + 1, // Add 1 (0-based month)13 local->tm_mday);14 printf(" Time: %02d:%02d:%02d\n",15 local->tm_hour, local->tm_min, local->tm_sec);16 17 // Convert to UTC time18 struct tm *utc = gmtime(&now);19 printf("\nUTC Time:\n");20 printf(" Date: %d-%02d-%02d\n",21 utc->tm_year + 1900, utc->tm_mon + 1, utc->tm_mday);22 printf(" Time: %02d:%02d:%02d\n",23 utc->tm_hour, utc->tm_min, utc->tm_sec);24 25 return 0;26}Local Time:
Date: 2024-12-15
Time: 18:30:45
UTC Time:
Date: 2024-12-15
Time: 13:00:45
💡 Accessing Individual Components
Use the arrow operator (->) to access struct tm members:local->tm_hour, local->tm_min, etc.
05ctime() and asctime() - Quick String Conversion
ctime() - time_t to String
Output format: Day Mon DD HH:MM:SS YYYY\n
asctime() - struct tm to String
Same format as ctime(), but takes struct tm* instead of time_t*
1#include <stdio.h>2#include <time.h>34int main() {5 time_t now = time(NULL);6 7 // ctime: time_t → string (includes newline)8 printf("ctime: %s", ctime(&now));9 10 // asctime: struct tm → string11 struct tm *local = localtime(&now);12 printf("asctime: %s", asctime(local));13 14 // Both produce the same output!15 return 0;16}ctime: Sun Dec 15 18:30:45 2024
asctime: Sun Dec 15 18:30:45 2024
⚠️ Note
Both ctime() and asctime()return a pointer to a static buffer. The string includes a newline \n at the end.
06strftime() - Custom Formatting
strftime() - Custom Format Time String
🏷️ Common Format Specifiers
| Specifier | Meaning | Example |
|---|---|---|
| %Y | Year (4 digits) | 2024 |
| %y | Year (2 digits) | 24 |
| %m | Month (01-12) | 12 |
| %B | Month name (full) | December |
| %b | Month name (short) | Dec |
| %d | Day (01-31) | 15 |
| %A | Weekday (full) | Sunday |
| %a | Weekday (short) | Sun |
| %H | Hour 24h (00-23) | 18 |
| %I | Hour 12h (01-12) | 06 |
| %M | Minute (00-59) | 30 |
| %S | Second (00-60) | 45 |
| %p | AM/PM | PM |
| %Z | Timezone name | IST |
1#include <stdio.h>2#include <time.h>34int main() {5 time_t now = time(NULL);6 struct tm *local = localtime(&now);7 char buffer[100];8 9 // Format 1: YYYY-MM-DD10 strftime(buffer, sizeof(buffer), "%Y-%m-%d", local);11 printf("ISO Date: %s\n", buffer);12 13 // Format 2: DD/MM/YYYY14 strftime(buffer, sizeof(buffer), "%d/%m/%Y", local);15 printf("Date: %s\n", buffer);16 17 // Format 3: Full date and time18 strftime(buffer, sizeof(buffer), "%A, %B %d, %Y", local);19 printf("Full: %s\n", buffer);20 21 // Format 4: 12-hour time with AM/PM22 strftime(buffer, sizeof(buffer), "%I:%M:%S %p", local);23 printf("Time: %s\n", buffer);24 25 // Format 5: 24-hour time26 strftime(buffer, sizeof(buffer), "%H:%M:%S", local);27 printf("24h Time: %s\n", buffer);28 29 return 0;30}ISO Date: 2024-12-15
Date: 15/12/2024
Full: Sunday, December 15, 2024
Time: 06:30:45 PM
24h Time: 18:30:45
07difftime() - Calculate Time Difference
difftime() - Calculate Time Difference
1#include <stdio.h>2#include <time.h>34int main() {5 time_t start, end;6 double elapsed;7 8 // Record start time9 time(&start);10 11 // Simulate some work (count to 100 million)12 printf("Working...\n");13 long sum = 0;14 for (long i = 0; i < 100000000; i++) {15 sum += i;16 }17 18 // Record end time19 time(&end);20 21 // Calculate difference22 elapsed = difftime(end, start);23 printf("Elapsed time: %.2f seconds\n", elapsed);24 25 return 0;26}Working...
Elapsed time: 1.00 seconds
08mktime() - Create Custom Time
mktime() - struct tm to time_t
Converts a filled struct tm to time_t. Also normalizes out-of-range values and fills in tm_wday and tm_yday.
1#include <stdio.h>2#include <time.h>34int main() {5 struct tm birthday = {0}; // Initialize all fields to 06 7 // Set a specific date: January 26, 2025, 10:30:008 birthday.tm_year = 2025 - 1900; // Years since 19009 birthday.tm_mon = 0; // January (0-based)10 birthday.tm_mday = 26; // Day 2611 birthday.tm_hour = 10;12 birthday.tm_min = 30;13 birthday.tm_sec = 0;14 15 // Convert to time_t16 time_t birthdayTime = mktime(&birthday);17 18 if (birthdayTime == -1) {19 printf("Error converting time!\n");20 return 1;21 }22 23 // Display the created time24 printf("Birthday: %s", ctime(&birthdayTime));25 26 // Calculate days until birthday27 time_t now = time(NULL);28 double daysUntil = difftime(birthdayTime, now) / (60 * 60 * 24);29 printf("Days until birthday: %.0f\n", daysUntil);30 31 return 0;32}Birthday: Sun Jan 26 10:30:00 2025
Days until birthday: 42
💡 mktime() Also Normalizes
If you set tm_mday = 32, mktime() will automatically adjust to the first day of the next month. It also fills in tm_wdayand tm_yday!
09clock() - Measure CPU Time
clock() - CPU Clock Ticks
Divide by CLOCKS_PER_SEC (macro) to get seconds. More precise than difftime() for benchmarking!
⚡ Formula
1#include <stdio.h>2#include <time.h>34int main() {5 clock_t start, end;6 double cpu_time;7 8 // Record start clock9 start = clock();10 11 // Do some computation12 printf("Calculating...\n");13 double result = 0;14 for (int i = 0; i < 10000000; i++) {15 result += i * 0.001;16 }17 18 // Record end clock19 end = clock();20 21 // Calculate CPU time in seconds22 cpu_time = ((double)(end - start)) / CLOCKS_PER_SEC;23 24 printf("Result: %.2f\n", result);25 printf("CPU Time: %.4f seconds\n", cpu_time);26 printf("Clock ticks: %ld\n", (long)(end - start));27 28 return 0;29}Calculating...
Result: 49999995000000.00
CPU Time: 0.0312 seconds
Clock ticks: 31250
✅ Use clock() for
- • Benchmarking code performance
- • Measuring CPU usage
- • Sub-second precision needed
✅ Use difftime() for
- • Wall-clock (real) time
- • User-facing countdowns
- • Date/time calculations
10Practical Example: Simple Logger
1#include <stdio.h>2#include <time.h>34void log_message(const char *level, const char *message) {5 time_t now = time(NULL);6 struct tm *local = localtime(&now);7 char timestamp[20];8 9 // Format: [2024-12-15 18:30:45]10 strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", local);11 12 printf("[%s] [%s] %s\n", timestamp, level, message);13}1415int main() {16 log_message("INFO", "Application started");17 log_message("DEBUG", "Loading configuration");18 log_message("INFO", "Server listening on port 8080");19 log_message("WARN", "High memory usage detected");20 log_message("ERROR", "Failed to connect to database");21 log_message("INFO", "Application shutting down");22 23 return 0;24}[2024-12-15 18:30:45] [INFO] Application started
[2024-12-15 18:30:45] [DEBUG] Loading configuration
[2024-12-15 18:30:45] [INFO] Server listening on port 8080
[2024-12-15 18:30:45] [WARN] High memory usage detected
[2024-12-15 18:30:45] [ERROR] Failed to connect to database
[2024-12-15 18:30:45] [INFO] Application shutting down
11Common Mistakes
❌ Forgetting tm_year and tm_mon Offsets
birthday.tm_year = 2024;
birthday.tm_mon = 12;
birthday.tm_year = 2024 - 1900;
birthday.tm_mon = 11;
❌ Not Initializing struct tm
struct tm t = {0};
Uninitialized fields contain garbage values.
❌ strftime Buffer Too Small
char buf[10];
char buf[100];
12Summary
🎯 Key Takeaways
- •
time()— Get current time as time_t - •
localtime()/gmtime()— Convert to struct tm - •
ctime()/asctime()— Quick string conversion - •
strftime()— Custom formatting (most flexible) - •
difftime()— Calculate time difference - •
mktime()— Create time from components - •
clock()— Precise CPU timing
time_t now = time(NULL);
struct tm *t = localtime(&now);
strftime(buf, 100, "%Y-%m-%d", t);
12Next Steps
Learn about UNIX/Linux system calls: