How to Calculate Age in C++ (chrono and Birthday Logic Examples)
Learn how to calculate age from date of birth in C++ using chrono plus a simple month-day birthday check.
How to Calculate Age in C++ (chrono and Birthday Logic Examples)
Age in C++ is usually the number of completed years. The basic pattern is simple: subtract years, then reduce by one if the birthday has not happened yet this year.
Fast option: use an online age calculator
If you want to verify the answer, or you need an exact result in years, months, and days, use a calculator first and then mirror the logic in code.
Open the age calculator and enter the date of birth plus the reference date.
Simple C++ example
This example uses a plain birthday check. It is enough for many apps and coding tasks.
struct Date {
int year;
int month;
int day;
};
int ageYears(const Date& dob, const Date& asOf) {
int years = asOf.year - dob.year;
if (asOf.month < dob.month || (asOf.month == dob.month && asOf.day < dob.day)) {
years--;
}
return years;
}
Using chrono for the current date
You can get today from std::chrono and then pass the parts into the same age function.
#include <chrono>
auto today = std::chrono::floor<std::chrono::days>(std::chrono::system_clock::now());
// Extract year, month, day and compare with dob
FAQ
Is there a built-in age function in C++?
No. Usually you store the birth date, compare it with the reference date, and adjust if the birthday has not happened yet.
What about leap-year birthdays?
For February 29 birthdays, decide whether your app treats February 28 or March 1 as the birthday in non-leap years, then test that rule.