C time.h Header

Date and time manipulation functions

⏰ What is time.h?

The time.h header provides functions for working with dates and times. It includes functions to get current time, format dates, measure execution time, and perform time calculations in C programs.


#include <time.h>

int main() {
    time_t current_time = time(NULL);
    printf("Current time: %s", ctime(& current_time));
    return 0;
}
                                    

Sample Output:

Current time: Wed Oct 25 14:30:45 2023

Key time.h Functions

🕐

time()

Get current time in seconds

time_t now = time(NULL);
📅

ctime()

Convert time to string format

char *str = ctime(& now);
⏱️

clock()

Measure program execution time

clock_t start = clock();
🗓️

strftime()

Format time as custom string

strftime(buffer, 80, "%Y-%m-%d", tm);

🔹 Getting Current Date and Time

C provides comprehensive date and time functions through the time.h library for accessing and displaying temporal information. The time() function returns the current time as seconds since the Unix epoch (January 1, 1970), while ctime() converts this timestamp to a human-readable string. For more control, localtime() converts the timestamp to a struct tm containing individual date and time components, and strftime() formats this structure with custom format specifiers. For example, strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_info); creates ISO 8601 formatted timestamps, essential for logging, scheduling, and time-based calculations in applications.

#include <stdio.h>
#include <time.h>

int main() {
    time_t current_time;
    struct tm *time_info;
    char time_string[80];
    
    // Get current time
    time(& current_time);
    
    // Convert to local time structure
    time_info = localtime(& current_time);
    
    // Display in default format (ctime already adds a newline)
    printf("Default format: %s", ctime(& current_time));
    
    // Custom formatted time
    strftime(time_string, sizeof(time_string), "Date: %Y-%m-%d", time_info);
    printf("%s\n", time_string);
    
    strftime(time_string, sizeof(time_string), "Time: %H:%M:%S", time_info);
    printf("%s\n", time_string);
    
    strftime(time_string, sizeof(time_string), "Day: %A, %B %d, %Y", time_info);
    printf("%s\n", time_string);
    
    return 0;
}

Sample Output:

Default format: Wed Oct 25 14:30:45 2023
Date: 2023-10-25
Time: 14:30:45
Day: Wednesday, October 25, 2023

🔹 Measuring Execution Time

Measuring execution time helps profile program performance and identify bottlenecks using the time.h and clock() functions. The clock() function returns processor time consumed by the program, which when divided by CLOCKS_PER_SEC gives elapsed time in seconds. For example, recording clock() before and after a code section, then computing the difference, reveals how long that operation takes. This is invaluable for optimization work, allowing developers to compare algorithm implementations, identify slow operations, and measure the impact of code changes. For more precise measurements, modern systems offer higher-resolution timing functions like clock_gettime() with nanosecond precision.

#include <stdio.h>
#include <time.h>

int main() {
    clock_t start, end;
    double cpu_time_used;
    
    // Record start time
    start = clock();
    
    // Simulate some work (counting to 1 million)
    printf("Performing calculation...\n");
    long sum = 0;
    for (long i = 0; i < 1000000; i++) {
        sum += i;
    }
    
    // Record end time
    end = clock();
    
    // Calculate execution time
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    
    printf("Sum calculated: %ld\n", sum);
    printf("Execution time: %f seconds\n", cpu_time_used);
    
    return 0;
}

Sample Output:

Performing calculation...
Sum calculated: 499999500000
Execution time: 0.003250 seconds

🔹 Working with Time Structures

The struct tm structure in C provides detailed access to individual components of dates and times for precise temporal calculations. This structure contains integer fields for year, month, day, hour, minute, second, and additional components like day of week and daylight saving time status. Functions like localtime() and gmtime() populate this structure from timestamp values, while mktime() converts a filled structure back to a timestamp. For example, accessing tm_info->tm_year + 1900 gives the current four-digit year since tm_year stores years since 1900. This granular access enables custom date arithmetic, calendar calculations, and scheduling algorithms.

#include <stdio.h>
#include <time.h>

int main() {
    time_t current_time;
    struct tm *time_info;
    
    time(& current_time);
    time_info = localtime(&current_time);
    
    printf("Current Date and Time Components:\n");
    printf("Year: %d\n", time_info->tm_year + 1900); // Years since 1900
    printf("Month: %d (%s)\n", time_info->tm_mon + 1, 
           (time_info->tm_mon == 0) ? "January" : 
           (time_info->tm_mon == 1) ? "February" : "...");
    printf("Day: %d\n", time_info->tm_mday);
    printf("Hour: %d\n", time_info->tm_hour);
    printf("Minute: %d\n", time_info->tm_min);
    printf("Second: %d\n", time_info->tm_sec);
    printf("Day of week: %d (0=Sunday)\n", time_info->tm_wday);
    printf("Day of year: %d\n", time_info->tm_yday + 1);
    
    return 0;
}

Sample Output:

Current Date and Time Components:
Year: 2023
Month: 10 (...)
Day: 25
Hour: 14
Minute: 30
Second: 45
Day of week: 3 (0=Sunday)
Day of year: 298

🧠 Test Your Knowledge

Which function gets the current time?