gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:52:31 25 4
gpt4 key购买 nike

我的目标是按照输入的生日检查用户的年龄,如果用户不超过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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com