如何在颤振中进行年龄验证

Iva*_*ius 6 validation date dart flutter

我的目标是通过输入的生日检查用户年龄,如果用户不是 18 岁或以上,则返回错误。但我不知道该怎么做。日期格式为“dd-MM-yyyy”。任何想法如何做到这一点?

Bok*_*ken 8

包裹

为了轻松解析日期,我们需要包intl

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

所以将此依赖项添加到你的pubspec.yaml文件(和get新的依赖项)

解决方案#1

您可以简单地比较年份:

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;
}
Run Code Online (Sandbox Code Playgroud)

但这并不总是正确的,因为到今年年底你还“不成熟”。

解决方案#2

所以更好的解决方案是将出生日期提前 18 天并与当前日期进行比较。

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);
}
Run Code Online (Sandbox Code Playgroud)