Introduction
The Age Calculator computes a person's exact age in years, months, and days from their date of birth. It demonstrates DateTime arithmetic, property getters, validation, and birthday countdown.
Full Code
class AgeCalculator {
final DateTime birthDate;
AgeCalculator(this.birthDate) {
if (birthDate.isAfter(DateTime.now())) {
throw ArgumentError('Birth date cannot be in the future');
}
}
int get years {
final now = DateTime.now();
int age = now.year - birthDate.year;
if (now.month < birthDate.month ||
(now.month == birthDate.month && now.day < birthDate.day)) age--;
return age;
}
int get months {
final now = DateTime.now();
int m = now.month - birthDate.month;
if (now.day < birthDate.day) m--;
return m < 0 ? m + 12 : m;
}
int get days {
final now = DateTime.now();
int d = now.day - birthDate.day;
return d < 0 ? DateTime(now.year, now.month, 0).day + d : d;
}
DateTime get nextBirthday {
final now = DateTime.now();
var next = DateTime(now.year, birthDate.month, birthDate.day);
if (!next.isAfter(now)) next = DateTime(now.year + 1, birthDate.month, birthDate.day);
return next;
}
int get daysUntilBirthday => nextBirthday.difference(DateTime.now()).inDays;
void printAge() {
print('Age: $years years, $months months, $days days');
print('Next birthday: $${nextBirthday.toString().substring(0, 10)}');
print('Days until birthday: $daysUntilBirthday');
}
}
void main() {
var p1 = AgeCalculator(DateTime(1995, 8, 15));
print('Born Aug 15, 1995:'); p1.printAge();
print('');
var p2 = AgeCalculator(DateTime(2000, 1, 1));
print('Born Jan 1, 2000:'); p2.printAge();
try {
AgeCalculator(DateTime(2099, 1, 1));
} on ArgumentError catch (e) {
print('Error: $${e.message}');
}
}
🧠 Quiz
1. Which Dart class handles date and time?
- A) Date
- B) Calendar
- C) DateTime ✅
- D) Time
2. How do you get the current date/time?
- A) DateTime.current()
- B) DateTime.now() ✅
- C) DateTime.today()
- D) DateTime.instance()
Summary
The Age Calculator uses DateTime arithmetic to compute exact age. Property getters (years, months, days, nextBirthday) make the API clean and readable. Constructor validation prevents logically impossible birth dates. Extend it with total-days calculation, birthday detection, and string date parsing.