C Date & Time
In this page:
The time.h Header
The time.h header supplies the core types and functions C uses to work with calendar dates and times, most notably the time_t type for representing a single point in time and the struct tm type for representing that same point broken down into individual fields like year, month, and day.
Example: The time.h Header
#include <stdio.h>
#include <time.h>
int main() {
time_t now;
struct tm *info;
printf("time.h provides time_t and struct tm");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Getting Current Time
time() returns the current calendar time as a time_t value, measured as the number of seconds that have elapsed since the Unix epoch (midnight, January 1, 1970 UTC) — a single portable number that other time.h functions can then convert into more human-friendly forms.
Example: Getting Current Time
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
printf("%d", now > 0);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Formatting with ctime()
ctime() converts a raw time_t value into a ready-made, human-readable string containing the day of the week, month, date, time of day, and year, sparing you from manually assembling those pieces yourself, though its exact output format is fixed and not customizable.
Example: Formatting with ctime()
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
printf("%s", ctime(&now));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Deconstructing Dates with localtime()
localtime() takes a time_t value and expands it into a struct tm with separate fields for the year, month, day, hour, minute, and second (all adjusted for the local time zone), which is what you need whenever you want to inspect or work with just one piece of a date rather than the whole thing at once.
Example: Deconstructing Dates with localtime()
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *local = localtime(&now);
printf("%d", local->tm_year + 1900);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Custom Formats with strftime()
strftime() builds a custom-formatted date string using format specifiers similar to printf, such as %Y for the four-digit year or %B for the full month name, giving you complete control over a date's displayed format instead of being limited to ctime()'s single fixed layout.
Example: Custom Formats with strftime()
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *local = localtime(&now);
char buffer[30];
strftime(buffer, 30, "%Y-%B", local);
printf("%s", buffer);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: