C++ Date and Time
In this page:
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
#include <iostream>
#include <ctime>
int main() {
time_t now = time(0);
std::cout << "Seconds since epoch: " << now << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <ctime>
int main() {
time_t now = time(0);
std::cout << ctime(&now);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: