How I calculate age in flutter get date from datepicker?

Viewed 43

I built datepicker function. when the date selected then should calculate the age and should display date and age. The date display correctly but age not show.

code

ElevatedButton(
        onPressed: () {
          send();
          calAge();
        },
        child: const Text("submit"),
      ),
      Text(selectedDate == null ? "" : "$age"),



void calAge(DateTime birthDate) {
  
      DateTime currentDate = DateTime.now();
      int age = currentDate.year - birthDate.year;
      int month1 = currentDate.month;
      int month2 = birthDate.month;
      if (month2 > month1) {
        age--;
      } else if (month1 == month2) {
        int day1 = currentDate.day;
        int day2 = birthDate.day;
        if (day2 > day1) {
          age--;
        }
      }
      return age;
   
  }
2 Answers

You can Create a userAge Function and get Difference with help of .difference method.

void main() {
  print(userAge(DateTime.now(),DateTime(2000, 06, 02)));
}

userAge(DateTime curruntDate, DateTime UsersBirthDate) {
    Duration parse = curruntDate.difference(UsersBirthDate).abs();
    return "${parse.inDays~/360} Years ${((parse.inDays%360)~/30)} Month ${(parse.inDays%360)%30} Days";
  }

You can use this package, https://pub.dev/packages/age_calculator/

ElevatedButton(
        onPressed: () {
          send();
          calAge();
        },
        child: const Text("submit"),
      ),
      Text(selectedDate == null ? "" : "$age"),



      DateDuration calAge(DateTime birthDate) {
 
       DateTime birthday =birthDate  //DateTime(1997, 3, 5); 

  

       DateDuration duration;
    
      // Find out your age as of today's date 2021-03-08
      duration = AgeCalculator.age(birthday);
      print('Your age is $duration')
          return duration ;

   
  }
Related