← Back to C++ Course | Chapter 15: File I/O | Lesson 6 of 6

C++ Date and Time

The <ctime> library provides functions like time() and localtime() for working with dates and times in C++, letting a program capture the current moment and format it for display.

Getting the Current Time

The time() function from <ctime> returns the current time as the number of seconds elapsed since January 1, 1970, commonly called Unix time or epoch time.

Example: Getting the Current Time

cpp
#include <iostream>
#include <ctime>

int main() {
	time_t now = time(0);
	std::cout << "Seconds since epoch: " << now << std::endl;
	return 0;
}

Converting to a Readable Date

ctime() converts a time_t value into a human-readable string showing the day, date, and time, making the raw epoch number understandable at a glance.

Example: Converting to a Readable Date

cpp
#include <iostream>
#include <ctime>

int main() {
	time_t now = time(0);
	std::cout << ctime(&now);
	return 0;
}

Breaking Down a Date with struct tm

localtime() breaks a time_t value down into a struct tm, exposing individual fields like year, month, day, hour, and minute for direct access.

Example: Breaking Down a Date with struct tm

cpp
#include <iostream>
#include <ctime>

int main() {
	time_t now = time(0);
	tm *local = localtime(&now);
	std::cout << "Year: " << (local->tm_year + 1900) << std::endl;
	return 0;
}

Formatting Dates with strftime

strftime() formats a struct tm into a custom string using format specifiers similar to printf, giving full control over exactly how a date and time are displayed.

Example: Formatting Dates with strftime

cpp
#include <iostream>
#include <ctime>

int main() {
	time_t now = time(0);
	tm *local = localtime(&now);
	char buffer[50];
	strftime(buffer, sizeof(buffer), "%Y-%m-%d", local);
	std::cout << buffer << std::endl;
	return 0;
}

Measuring Elapsed Time

Subtracting two time_t values, or using difftime(), calculates how many seconds elapsed between two points in time, useful for measuring durations or program run time.

Example: Measuring Elapsed Time

cpp
#include <iostream>
#include <ctime>

int main() {
	time_t start = time(0);
	time_t end = start + 5;
	std::cout << difftime(end, start) << " seconds elapsed" << std::endl;
	return 0;
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

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.