← Back to C Course | Chapter 14: Additional Topics | Lesson 7 of 9

C Date & Time

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

c
#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;
}

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

c
#include <stdio.h>
#include <time.h>
int main() {
	time_t now = time(NULL);
	printf("%d", now > 0);
	return 0;
}

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()

c
#include <stdio.h>
#include <time.h>
int main() {
	time_t now = time(NULL);
	printf("%s", ctime(&now));
	return 0;
}

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()

c
#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;
}

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()

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.