time() Function Example in C Programming

In this source code example, we will see how to use the time() function in C programming with an example.

time() Function Overview

The time() function in C returns the current calendar time of the system. This time is represented as the number of seconds elapsed since the Epoch (1970-01-01 00:00:00 UTC). 

It is a core function when dealing with date and time operations in C and serves as a foundation for more complex operations, such as date arithmetic or formatting. The function can be found in the time.h library. 

Key Points:

- To utilize the time() function, you need to include the time.h header. 

- The function returns the time as time_t type, which typically represents the time in seconds. 

- It can be used to generate a seed for random number generation, benchmark code, or simply retrieve the system time.

Source Code Example

#include <stdio.h>
#include <time.h>  // Necessary for time()

int main() {
    time_t current_time;

    // Get the current calendar time
    current_time = time(NULL);

    if (current_time == (time_t)-1) {
        printf("Failed to fetch the current time.\n");
        return 1;
    }

    // Display the number of seconds since the Epoch
    printf("Number of seconds since the Epoch: %lld\n", (long long) current_time);

    return 0;
}

Output

Number of seconds since the Epoch: 1672912304
(Note: The output will differ each time the program runs due to the changing current time.)

Explanation

1. The necessary header files are included: stdio.h for input/output functions and time.h for the time() function.

2. In the main() function, the time() function is called to fetch the current calendar time.

3. We check for any errors in fetching the time. If the function fails, it returns (time_t)-1.

4. The number of seconds elapsed since the Epoch is then displayed. For systems where time_t is represented as a long int, we cast it to long long for portable printing.

The returned time, in seconds since the Epoch, can be further converted into a human-readable format using other functions from the time.h library, such as localtime() or gmtime().


Comments