calculateAge static method

DigitDOBAge calculateAge(
  1. DateTime? selectedDate
)

Implementation

static DigitDOBAge calculateAge(DateTime? selectedDate) {
  if (selectedDate == null) {
    return DigitDOBAge();
  } else {
    DateTime currentDate = DateTime.now();

    // Calculate the difference in years, months, and days
    int ageInYears = currentDate.year - selectedDate.year;
    int ageInMonths = currentDate.month - selectedDate.month;
    int ageInDays = currentDate.day - selectedDate.day;

    // If the current day is earlier than the selected day in the same month,
    // reduce the month count and adjust the days accordingly.
    if (ageInDays < 0) {
      ageInMonths--;
      ageInDays += DateTime(selectedDate.year, selectedDate.month + 1, 0).day;
    }

    // If the current month is earlier than the selected month, reduce the year count
    // and adjust the month and day counts accordingly.
    if (ageInMonths < 0) {
      ageInYears--;
      ageInMonths += 12;
    }

    return DigitDOBAge(
        years: ageInYears >= 0 ? ageInYears : 0,
        months: ageInMonths,
        days: ageInDays);
  }
}