Chapter 31Intermediate

C time.h Library Reference

Complete reference for time.h - getting time, formatting dates, measuring durations, and working with timestamps.

18 min readUpdated 2024-12-16
time.htimelocaltimestrftimedifftimeclock

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

FunctionPrototypeDescription
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
time_intro.c
C
1#include <stdio.h>
2#include <time.h> // Include for time functions
3
4int main() {
5 // Get current time
6 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_sec

Seconds (0-60)

tm_min

Minutes (0-59)

tm_hour

Hours (0-23)

tm_mday

Day of month (1-31)

tm_mon

Month (0-11)

tm_year

Years since 1900

tm_wday

Day of week (0=Sun)

tm_yday

Day of year (0-365)

tm_isdst

Daylight saving flag

⚠️ Important Notes

  • tm_mon is 0-based: January = 0, December = 11
  • tm_year is years since 1900: 2024 = 124

03time() - Get Current Time

time() - Get Current Calendar Time

time_t time(time_t *timer);
timer: Pointer to store result (or NULL)
Returns: Current time as time_t, or -1 on error

Returns seconds since January 1, 1970 00:00:00 UTC (Unix Epoch). If timer is not NULL, the result is also stored in *timer.

time_function.c
C
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 // Method 1: Pass NULL, use return value
6 time_t now = time(NULL);
7 printf("Seconds since Jan 1, 1970: %ld\n", now);
8
9 // Method 2: Pass pointer to store result
10 time_t current;
11 time(&current);
12 printf("Same value: %ld\n", current);
13
14 return 0;
15}
Output (example)

Seconds since Jan 1, 1970: 1734278400

Same value: 1734278400

04localtime() and gmtime()

localtime() - Convert to Local Time

struct tm *localtime(const time_t *timer);
timer: Pointer to time_t value
Returns: Pointer to struct tm (local timezone)

gmtime() - Convert to UTC Time

struct tm *gmtime(const time_t *timer);
timer: Pointer to time_t value
Returns: Pointer to struct tm (UTC/GMT)
localtime_gmtime.c
C
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 time_t now = time(NULL);
6
7 // Convert to local time
8 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 year
12 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 time
18 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}
Output (example - IST timezone)

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

char *ctime(const time_t *timer);
timer: Pointer to time_t value
Returns: Pointer to static string buffer

Output format: Day Mon DD HH:MM:SS YYYY\n

asctime() - struct tm to String

char *asctime(const struct tm *tm);
tm: Pointer to struct tm
Returns: Pointer to static string buffer

Same format as ctime(), but takes struct tm* instead of time_t*

ctime_asctime.c
C
1#include <stdio.h>
2#include <time.h>
3
4int 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 → string
11 struct tm *local = localtime(&now);
12 printf("asctime: %s", asctime(local));
13
14 // Both produce the same output!
15 return 0;
16}
Output

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

size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *tm);
str: Destination buffer for result
maxsize: Max bytes to write (including \\0)
format: Format string with specifiers
tm: Pointer to struct tm
Returns: Number of characters written (excluding \\0), or 0 on error

🏷️ Common Format Specifiers

SpecifierMeaningExample
%YYear (4 digits)2024
%yYear (2 digits)24
%mMonth (01-12)12
%BMonth name (full)December
%bMonth name (short)Dec
%dDay (01-31)15
%AWeekday (full)Sunday
%aWeekday (short)Sun
%HHour 24h (00-23)18
%IHour 12h (01-12)06
%MMinute (00-59)30
%SSecond (00-60)45
%pAM/PMPM
%ZTimezone nameIST
strftime_example.c
C
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 time_t now = time(NULL);
6 struct tm *local = localtime(&now);
7 char buffer[100];
8
9 // Format 1: YYYY-MM-DD
10 strftime(buffer, sizeof(buffer), "%Y-%m-%d", local);
11 printf("ISO Date: %s\n", buffer);
12
13 // Format 2: DD/MM/YYYY
14 strftime(buffer, sizeof(buffer), "%d/%m/%Y", local);
15 printf("Date: %s\n", buffer);
16
17 // Format 3: Full date and time
18 strftime(buffer, sizeof(buffer), "%A, %B %d, %Y", local);
19 printf("Full: %s\n", buffer);
20
21 // Format 4: 12-hour time with AM/PM
22 strftime(buffer, sizeof(buffer), "%I:%M:%S %p", local);
23 printf("Time: %s\n", buffer);
24
25 // Format 5: 24-hour time
26 strftime(buffer, sizeof(buffer), "%H:%M:%S", local);
27 printf("24h Time: %s\n", buffer);
28
29 return 0;
30}
Output

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

double difftime(time_t end, time_t start);
end: End time (time_t)
start: Start time (time_t)
Returns: Difference in seconds (end - start)
difftime_example.c
C
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 time_t start, end;
6 double elapsed;
7
8 // Record start time
9 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 time
19 time(&end);
20
21 // Calculate difference
22 elapsed = difftime(end, start);
23 printf("Elapsed time: %.2f seconds\n", elapsed);
24
25 return 0;
26}
Output

Working...

Elapsed time: 1.00 seconds

08mktime() - Create Custom Time

mktime() - struct tm to time_t

time_t mktime(struct tm *tm);
tm: Pointer to struct tm (you fill in)
Returns: time_t value, or -1 on error

Converts a filled struct tm to time_t. Also normalizes out-of-range values and fills in tm_wday and tm_yday.

mktime_example.c
C
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 struct tm birthday = {0}; // Initialize all fields to 0
6
7 // Set a specific date: January 26, 2025, 10:30:00
8 birthday.tm_year = 2025 - 1900; // Years since 1900
9 birthday.tm_mon = 0; // January (0-based)
10 birthday.tm_mday = 26; // Day 26
11 birthday.tm_hour = 10;
12 birthday.tm_min = 30;
13 birthday.tm_sec = 0;
14
15 // Convert to time_t
16 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 time
24 printf("Birthday: %s", ctime(&birthdayTime));
25
26 // Calculate days until birthday
27 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}
Output

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

clock_t clock(void);
Arguments: None
Returns: CPU clock ticks since program start

Divide by CLOCKS_PER_SEC (macro) to get seconds. More precise than difftime() for benchmarking!

⚡ Formula

seconds = (end_clock - start_clock) / CLOCKS_PER_SEC
clock_example.c
C
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 clock_t start, end;
6 double cpu_time;
7
8 // Record start clock
9 start = clock();
10
11 // Do some computation
12 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 clock
19 end = clock();
20
21 // Calculate CPU time in seconds
22 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}
Output

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

simple_logger.c
C
1#include <stdio.h>
2#include <time.h>
3
4void 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}
14
15int 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}
Output

[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: