dart 如何在Flutter中进行时效验证

x6yk4ghg  于 2022-12-20  发布在  Flutter
关注(0)|答案(8)|浏览(174)

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

n3h0vuf2

n3h0vuf21#

Package

要轻松解析日期,我们需要包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;
}

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

溶液#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);
}
bz4sfanl

bz4sfanl2#

我所提出的最好的年龄验证是基于Regex的。

以下逻辑涵盖了所有与断点相关的年龄。

// regex for validation of date format : dd.mm.yyyy, dd/mm/yyyy, dd-mm-yyyy
RegExp regExp = new RegExp(
    r"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$",
    caseSensitive: true,
    multiLine: false,
  );

//method to calculate age on Today (in years)
  int ageCalculate(String input){
  if(regExp.hasMatch(input)){
  DateTime _dateTime = DateTime(
      int.parse(input.substring(6)),
      int.parse(input.substring(3, 5)),
      int.parse(input.substring(0, 2)),
    );
    return DateTime.fromMillisecondsSinceEpoch(
                DateTime.now().difference(_dateTime).inMilliseconds)
            .year -
        1970;
  } else{
    return -1;
  }
}

void main() {
// input values and validations examples
  var input = "29.02.2008";
  print("12.13.2029 : " + regExp.hasMatch("12.13.2029").toString());
  print("29.02.2028 : " + regExp.hasMatch("29.02.2028").toString());
  print("29.02.2029 : " + regExp.hasMatch("29.02.2029").toString());
  print("11/12-2019 : " + regExp.hasMatch("11/12-2019").toString());
  print("23/12/2029 : " + regExp.hasMatch("23/12/2029").toString());
  print("23/12/2029 : " + regExp.hasMatch(input).toString());
  print("sdssh : " + regExp.stringMatch("sdssh").toString());   
  print("age as per 29.02.2008 : " + ageCalculate(input).toString());
}

产出

12.13.2029 : false
 29.02.2028 : true
 29.02.2029 : false
 11/12-2019 : false
 23/12/2029 : true
 23/12/2029 : true
 sdssh : null
 age as per 29.02.2008 : 12

希望你会觉得这个有用。:)

atmip9wb

atmip9wb3#

您可以使用扩展添加一个函数,以检查DateTime。例如:

extension DateTimeX on DateTime {
  bool isUnderage() =>
      (DateTime(DateTime.now().year, this.month, this.day)
              .isAfter(DateTime.now())
          ? DateTime.now().year - this.year - 1
          : DateTime.now().year - this.year) < 18;
}

void main() {
  final today = DateTime.now();
  final seventeenY = DateTime(today.year - 18, today.month, today.day + 1);
  final eighteenY = DateTime(today.year - 18, today.month, today.day);
  
  print(today.isUnderage());
  print(seventeenY.isUnderage());
  print(eighteenY.isUnderage());
}

值得注意的是,这并不需要intl或任何其他外部封装。粘贴到dartpad.dev的权利,以测试出来。

v440hwme

v440hwme4#

你可以用下面的方法找出年差。

String _data = '16-04-2000';

    DateTime _dateTime = DateTime(
      int.parse(_data.substring(6)),
      int.parse(_data.substring(3, 5)),
      int.parse(_data.substring(0, 2)),
    );
    int yeardiff = DateTime.fromMillisecondsSinceEpoch(
                DateTime.now().difference(_dateTime).inMilliseconds)
            .year -
        1970;
    print(yeardiff);
bejyjqdl

bejyjqdl5#

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';     

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),      
    );
  }
}

class Home extends StatefulWidget {
  Home({Key key}) : super(key: key);

  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String dateFormate;
  @override
  Widget build(BuildContext context) {
     var dateNow = new DateTime.now();
     var givenDate = "1969-07-20";
     var givenDateFormat = DateTime.parse(givenDate);
     var diff = dateNow.difference(givenDateFormat);
     var year = ((diff.inDays)/365).round();

    return Container(
      child: (year < 18)?Text('You are under 18'):Text("$year years old"),
    );
  }
}
798qvoo8

798qvoo86#

如果你使用的是intl包,这是非常简单的。确保你已经为你的日期选择器和你验证年龄的函数设置了相同的格式。
您可以使用以下代码计算当天日期与输入日期之间的差值:

double isAdult(String enteredAge) {
    var birthDate = DateFormat('MMMM d, yyyy').parse(enteredAge);
    print("set state: $birthDate");
    var today = DateTime.now();

    final difference = today.difference(birthDate).inDays;
    print(difference);
    final year = difference / 365;
    print(year);
    return year;
  }

您可以在函数的返回值上创建一个条件,如下所示:

Container(
  child: (isAdult(selecteddate) < 18 ? Text("You are under age") : Text("$selecteddate is your current age")
)
bvjveswy

bvjveswy7#

18年有6570天,所以我创建了一个简单的操作来检查输入的日期与今天的日期相比是否大于6570天。

DateTime.now().difference(date) < Duration(days: 6570)

如果这是真的,则用户小于18岁,如果不是,则用户大于18岁。也在白天工作。
这是我的if块:

if (DateTime.now().difference(date) < Duration(days: 6570)) {
EasyLoading.showError('You should be 18 years old to register');} 
else {
store.changeBirthday(date);}
fumotvh3

fumotvh38#

import 'package:intl/intl.dart';

void main() {
  print(_isAdult('12-19-2004') ? 'over 18' : 'under 18');
}

bool _isAdult(String dob) {
  final dateOfBirth = DateFormat("MM-dd-yyyy").parse(dob);
  final now = DateTime.now();
  final eighteenYearsAgo = DateTime(
    now.year - 18,
    now.month,
    now.day + 1, // add day to return true on birthday
  );
  return dateOfBirth.isBefore(eighteenYearsAgo);
}

类似于@Broken的公认答案,但我认为这更具可读性。
DartPad https://dartpad.dev/?id=53885d812c90230f2a5b786e75b6cd82上的测试

相关问题