0
0
CHow-ToBeginner · 3 min read

How to Use time() Function in C: Syntax and Example

In C, use the time() function from time.h to get the current time as the number of seconds since January 1, 1970 (the Epoch). Call time(NULL) to get the current time as a time_t value.
📐

Syntax

The time() function returns the current time as a time_t value representing seconds since the Epoch (January 1, 1970). You can pass a pointer to a time_t variable to store the result, or pass NULL to get the value directly.

  • time_t time(time_t *timer);
  • timer: pointer to time_t variable or NULL
  • Returns current time as time_t or (time_t)(-1) on error
c
time_t time(time_t *timer);
💻

Example

This example shows how to get the current time using time(NULL) and print it as a number of seconds since the Epoch.

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

int main() {
    time_t current_time = time(NULL);
    if (current_time == (time_t)(-1)) {
        printf("Failed to get the current time.\n");
        return 1;
    }
    printf("Current time in seconds since the Epoch: %ld\n", (long)current_time);
    return 0;
}
Output
Current time in seconds since the Epoch: 1718821234
⚠️

Common Pitfalls

Common mistakes when using time() include:

  • Passing an invalid pointer instead of NULL or a valid time_t pointer.
  • Not checking if the return value is (time_t)(-1), which indicates an error.
  • Assuming the returned value is human-readable time instead of seconds since the Epoch.

Always cast time_t to long or use proper formatting when printing.

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

int main() {
    time_t t;
    // Wrong: passing uninitialized pointer
    // time_t *ptr; // Correct would be NULL or &t
    // time_t current = time(ptr); // This causes undefined behavior

    // Right way:
    time_t current = time(NULL);
    if (current == (time_t)(-1)) {
        printf("Error getting time\n");
        return 1;
    }
    printf("Time: %ld\n", (long)current);
    return 0;
}
📊

Quick Reference

Summary tips for using time() in C:

  • Include <time.h> to use time().
  • Call time(NULL) to get current time as time_t.
  • Check if return value is (time_t)(-1) for errors.
  • Use ctime() or localtime() to convert time_t to readable formats.

Key Takeaways

Use time(NULL) to get the current time as seconds since the Epoch.
Always check if time() returns (time_t)(-1) to detect errors.
Include <time.h> to use the time() function.
The returned time_t value is not human-readable; convert it with ctime() or localtime() if needed.
Avoid passing invalid pointers to time(); use NULL or a valid time_t pointer.