Back to Blog
2 min read

How to Calculate Age in Dart (DateTime and Birthday Logic Examples)

Learn how to calculate age from date of birth in Dart using DateTime, with a clean birthday check and a simple helper you can reuse.

How to Calculate Age in Dart (DateTime and Birthday Logic Examples)

In Dart, age usually means the number of completed years. The reliable pattern is simple: subtract birth year, then reduce by one if the birthday has not happened yet in the reference year.

Fast option: use an online age calculator

If you want a quick check, or you need an exact result in years, months, and days, verify the dates in a calculator first and then mirror the logic in code.

Open the age calculator and enter the date of birth plus the reference date.

Dart example with DateTime

This helper returns completed years as of a given date.

int ageYears(DateTime dob, [DateTime? asOf]) {
  final now = asOf ?? DateTime.now();
  int years = now.year - dob.year;

  final hadBirthday =
      now.month > dob.month ||
      (now.month == dob.month && now.day >= dob.day);

  if (!hadBirthday) years--;
  return years;
}

final dob = DateTime(1998, 10, 12);
print(ageYears(dob));

Parsing from a date string

If the input is already in ISO format like 1998-10-12, DateTime.parse() is often enough.

final dob = DateTime.parse('1998-10-12');
final years = ageYears(dob);

FAQ

Why not divide days by 365.25?

That can be fine for a rough estimate, but real age should follow birthdays. A direct birthday check avoids common off-by-one problems.

How do I calculate exact age in years, months, and days?

That is a separate problem because months have different lengths. It helps to validate your output against a dedicated calculator before wrapping it in app logic.

Related