calculateAge method

({int days, int months, int years}) calculateAge()

calculates the age of a person based on the current date

Implementation

({int years, int months, int days}) calculateAge() {
  // Helper function to determine the number of days in a month
  int daysInMonth(int year, int month) => DateTime(year, month + 1, 0).day;

  final birthDate = toLocal();
  final today = DateTime.now();

  // Check if birth date is Feb 29
  final isLeapDayBirthday = birthDate.month == 2 && birthDate.day == 29;

  // Adjust the birth day for non-leap years
  var birthDay = birthDate.day;
  if (isLeapDayBirthday && !today.isLeapYear) {
    birthDay = 28;
  }

  var years = today.year - birthDate.year;
  var months = today.month - birthDate.month;
  var days = today.day - birthDay;

  // Adjust days and months if necessary
  if (days < 0) {
    months -= 1;
    final prevMonth = (today.month - 1 == 0) ? 12 : today.month - 1;
    days += daysInMonth(today.year, prevMonth);
  }

  if (months < 0) {
    years -= 1;
    months += 12;
  }

  return (years: years, months: months, days: days);
}