C Date and Time
Time and Date
In C, you can use the <time.h>
header to work with dates and times.
This library lets you get the current time, format it, and perform time-related calculations.
Getting the Current Time
The <time.h>
library has a variety of functions to measure dates and times.
For example, the time()
function returns the current time as a value of type time_t
.
You can use ctime()
to convert the time into a readable string, like "Mon Jun 24 10:15:00 2025":
Example
#include <stdio.h>
#include <time.h>
int main() {
time_t currentTime;
time(¤tTime); // Get the current time
printf("Current time: %s", ctime(¤tTime));
return 0;
}
Breaking Down the Time
If you want to access individual parts of the date or time, like the year, month, or hour, you can use the localtime()
function.
This function converts the current time (from time()
) into a struct tm
, which is a special structure that holds the date and time in separate fields.
Here's how you can use it to print each part of the current date and time:
Example
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL); // Get current time
struct tm *t = localtime(&now); // Convert to local time structure
printf("Year: %d\n", t->tm_year + 1900); // Add 1900 to get the actual year
printf("Month: %d\n", t->tm_mon + 1); // Months are numbered from 0 to 11, so add 1 to match real month numbers (1-12)
printf("Day: %d\n", t->tm_mday);
printf("Hour: %d\n", t->tm_hour);
printf("Minute: %d\n", t->tm_min);
printf("Second: %d\n", t->tm_sec);
return 0;
}
Note: The tm_year
stores the number of years since 1900, so we add 1900 to get the full year, and tm_mon
starts from 0 (so 0 = January, 11 = December).
Note: We use ->
because localtime()
returns a pointer to a struct tm
.
As you learned in the Structs & Pointers chapter: If you have a pointer to a struct
, use ->
to access its members. Use the dot .
only when you're working with the struct directly, not a pointer to it.
Formatting Date and Time
You can use strftime()
to format the date and time as a string:
Example
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *t = localtime(&now);
char buffer[100];
strftime(buffer, sizeof(buffer), "%d-%m-%Y %H:%M:%S", t);
printf("Formatted time: %s\n", buffer);
return 0;
}
When to use Date and Time
Use date and time in C when you want to:
- Display the current time or date
- Log events like errors or user actions
- Add timestamps to files or messages
- Measure how long something takes
- Schedule or delay actions