如何在颤振中进行年龄验证 [英] How to make age validation in flutter

查看:72
本文介绍了如何在颤振中进行年龄验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

包装

要轻松解析日期,我们需要打包 intl :

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

因此将此依赖项添加到您的 pubspec.yaml 文件中(并 get 新的依赖项)

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

您可以简单比较年份:

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".

因此,更好的解决方案是将出生日提前18天并与当前日期进行比较.

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);
}

这篇关于如何在颤振中进行年龄验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆