Getting system time with time_t
What you'll learn: How to capture the current system time as a single numerical value using the time() function.
The "Seconds Since Ever" Counter
Computers don't naturally think in terms of months or weekdays. Instead, C tracks time as a giant, ticking counter. By default, most systems count the number of seconds that have passed since the "Unix Epoch": Midnight on January 1st, 1970.
To store this massive number, we use a special data type called time_t. You can think of time_t as a specialized container (usually a long integer) designed specifically to hold a timestamp.
Using the time() Function
To grab the current moment, we use the time() function from the <time.h> library. There are two ways to use it, but the most common way is to pass NULL as an argument. This tells the computer: "Just give me the current time right now; don't worry about storing it anywhere else."
Here is how you capture the system time and print it:
#include <stdio.h>
#include <time.h>
int main() {
// 1. Create a variable to hold the time
time_t now;
// 2. Capture the current system time
now = time(NULL);
// 3. Print the raw number of seconds
// Note: We cast to long for printing compatibility
printf("Seconds since Jan 1, 1970: %ld\n", (long)now);
return 0;
}
Why use time_t?
While a huge number like 1709241600 isn't easy for a human to read, it is incredibly useful for a programmer. Because it is just a number, you can easily calculate the difference between two points in time by subtracting them.
If you want to know how long a piece of code takes to run, you can capture the time at the start, capture it again at the end, and subtract the two. It is the "raw ingredient" of time management in C; once you have this number, you can later convert it into a human-readable format like "Monday at 5:00 PM."
Key takeaway
Use time_t to declare a time variable and time(NULL) to fill it with the current number of seconds elapsed since the Unix Epoch.