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 totime_tvariable orNULL- Returns current time as
time_tor(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
NULLor a validtime_tpointer. - 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 usetime(). - Call
time(NULL)to get current time astime_t. - Check if return value is
(time_t)(-1)for errors. - Use
ctime()orlocaltime()to converttime_tto 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.