Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

date - How to make age validation in flutter

My goal is to check users age by entered birthday and return error if user is not 18 years old or older. But i have no idea how to do that. Date format is "dd-MM-yyyy". Any ideas how to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Package

To easily parse date we need package intl:

https://pub.dev/packages/intl#-installing-tab-

So add this dependency to youd pubspec.yaml file (and get new dependencies)

Solution #1

You can just simple compare years:

bool isAdult(String birthDateString) {
  String datePattern = "dd-MM-yyyy";

  DateTime birthDate = DateFormat(datePattern).parse(birthDateString);
  DateTime today = DateTime.now();

  int yearDiff = today.year - birthDate.year;
  int monthDiff = today.month - birthDate.month;
  int dayDiff = today.day - birthDate.day;

  return yearDiff > 18 || yearDiff == 18 && monthDiff >= 0 && dayDiff >= 0;
}

But it's not always true, because to the end of current year you are "not adult".

Solution #2

So better solution is move birth day 18 ahead and compare with current date.

bool isAdult2(String birthDateString) {
  String datePattern = "dd-MM-yyyy";

  // Current time - at this moment
  DateTime today = DateTime.now();

  // Parsed date to check
  DateTime birthDate = DateFormat(datePattern).parse(birthDateString);

  // Date to check but moved 18 years ahead
  DateTime adultDate = DateTime(
    birthDate.year + 18,
    birthDate.month,
    birthDate.day,
  );

  return adultDate.isBefore(today);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...