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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…