date - 如何在 flutter 中进行年龄验证

标签 date validation flutter dart

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

最佳答案

包裹
为了轻松解析日期,我们需要打包intl:
https://pub.dev/packages/intl#-installing-tab-
因此,将此依赖项添加到youd 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;
}
但这并不总是正确的,因为到今年年底您还不是成年人。
解决方案#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);
}

关于date - 如何在 flutter 中进行年龄验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61249772/

相关文章:

java - 正在为如何在 Java 中比较不同时区的时间而烦恼吗?

date - oracle 日期时间的数据类型

mysql - 让 mySQL MONTH() 使用前导零?

php - MVC 模式中的验证层

flutter - 如何在flutter中实现相对字体大小?

java - 升级 android studio 破坏了我的 flutter build (macOS)

flutter - 为什么我在 flutter 中遇到这个错误?构造函数错误?

python 将字符串隐式转换为日期时间对象

javascript - Breeze:如何根据另一个属性的值验证一个属性

c# - MVC3 单选按钮验证