← Back to C Course | Chapter 12: Advanced Topics | Lesson 12 of 20

C time.h Functions

Getting Current Time

time() returns the current calendar time as the number of seconds elapsed since the Unix epoch (midnight, January 1, 1970 UTC), giving you a single portable integer value you can store, compare, or later convert into a readable date. It's the usual starting point for any time-related calculation in C.

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 Time as String

ctime() takes the raw time_t value returned by time() and formats it into a fixed, human-readable string containing the day of week, month, date, time, and year, saving you from manually assembling a date string yourself. The returned string already ends in a newline, which is easy to forget when concatenating it elsewhere.

Example: Formatting Time as String

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

Deconstructing Time

localtime() breaks a time_t value down into a struct tm with separate fields for year, month, day, hour, minute, and second, adjusted for the local time zone, so you can inspect or manipulate individual components of a date instead of working with the single opaque seconds-since-epoch number.

Example: Deconstructing Time

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

Measuring Execution Time

clock() reports how many CPU clock ticks have elapsed since the program itself started running, which is useful for measuring how long a specific piece of code takes to execute. Dividing the result by CLOCKS_PER_SEC converts that tick count into a number of seconds you can actually reason about.

Example: Measuring Execution Time

c
#include <stdio.h>
#include <time.h>
int main() {
	clock_t start = clock();
	for (int i = 0; i < 1000; i++) {}
	clock_t end = clock();
	printf("%d", end >= start);
	return 0;
}

Custom Time Formatting

strftime() lets you build a custom date string using format specifiers similar in spirit to printf's, such as %Y for a four-digit year or %H for a 24-hour-clock hour, giving you full control over exactly how a date is displayed instead of being limited to ctime()'s fixed format.

Example: Custom Time Formatting

c
#include <stdio.h>
#include <time.h>
int main() {
	time_t now = time(NULL);
	struct tm *local = localtime(&now);
	char buffer[20];
	strftime(buffer, 20, "%Y", 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.