HOME HTML EDITOR C JAVA PHP

C Date and Time: Handling Temporal Data

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.

1. Core Concepts: time_t and struct tm

To work with time in C, you need to understand the two primary ways data is stored:

2. Getting the Current Time

The time() function captures the current system time in seconds, which can then be converted into a readable format using ctime().

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

int main() {
    time_t t;
    time(&t); // Get current time

    printf("Current Time: %s", ctime(&t));
    return 0;
}

3. Working with struct tm

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).

4. Custom Formatting with strftime()

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.

char buffer[80];
struct tm *info;
time_t rawtime;

time(&rawtime);
info = localtime(&rawtime);

// Format: Day, Month Date, Year
strftime(buffer, 80, "%A, %B %d, %Y", info);
printf("Formatted Date: %s", buffer);

5. Measuring Execution Time

You can calculate how long a piece of code takes to run using the clock() function, which tracks processor cycles.

clock_t start = clock();
// ... some complex calculation ...
clock_t end = clock();

double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
printf("Time taken: %f seconds", time_spent);

6. Common Pitfalls

Pro Tip: When storing dates in a database or a file, always use Epoch Time (time_t). It is a single number, making it much easier to sort, compare, and calculate differences between two dates!