HOME HTML EDITOR C JAVA PHP

C time.h: Date and Time Functions

The <time.h> header provides functions to manipulate date and time. It tracks time as a count of seconds since the Epoch (January 1, 1970).

1. Core Data Types

Before using time functions, you must understand the two primary ways C stores time data:

Type Description
time_t Stores the total seconds since the Epoch (usually a long integer).
struct tm A structure holding components like year, month, day, hour, etc.
clock_t Used for measuring processor time (CPU clock cycles).

2. Getting the Current Time

To get the current system time, we use the time() function. To convert it into a human-readable string, we use ctime().

time_t now;
time(&now); // Get current time
printf("Current Time: %s", ctime(&now));

3. The 'tm' Structure Components

When you need to access specific details like the "Day of the week" or "Month," you use localtime() to fill a tm struct.

4. Measuring Execution Time

If you want to know how long a specific piece of code takes to run, use clock().

clock_t start = clock();
// ... perform some work ...
clock_t end = clock();
double cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

5. Advanced Formatting: strftime()

For professional applications, strftime() allows you to format the date exactly how you want (e.g., "YYYY-MM-DD").

char buffer[80];
struct tm *info = localtime(&now);
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
printf("Formatted: %s", buffer);

6. Summary of Key Functions

Pro Tip: Always remember that tm_year starts from 1900 and tm_mon starts from 0. Forgetting to add 1900 to the year is one of the most common bugs in C time programming!