【问题标题】:Check if date entered is less than 18 years old [duplicate]检查输入的日期是否小于 18 岁 [重复]
【发布时间】:2021-05-11 03:44:31
【问题描述】:

我设法得到了 18 年前的今天的日期:

var formatter = DateFormat('dd/MM/yyyy');

DateTime today = DateTime.now();
final eighteenY = DateTime(today.year - 18, today.month, today.day);

但现在我需要检查用户输入的日期是否在该日期和今天的日期之间,如果是,那么他们未超过 18 岁。我该怎么做?这是我的代码:


MaskedTextController _maskDOBController =
MaskedTextController(mask: '00/00/0000');

@override
  Widget build(BuildContext context) {

return Scaffold(

body:

return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
  Container(
    height: 48,
    width: 500,
    child: TextFormField(
      controller: _maskDOBController,
      onChanged: (string){
           setState(() {
             provider.dobString = string;
             dobError = false;
             });
           },
        ),
     ),
   ],
 ),
),

Container(height: 80),

Container(
  GestureDetector(
    onTap: (){
      // if the date a user enters in textfield is between that date and today's date
      // print('user is underage');
    }
    child: Text(
     'Continue'
    ),
  ),
);

【问题讨论】:

  • 这能回答你的问题吗? How to make age validation in flutter
  • 是的,完美,谢谢。我实际上并没有尝试过你的答案 - 但评论将我链接到该问题的第一个答案
  • 不客气!大多数解决方案都行得通,这完全取决于您喜欢什么语法。

标签: flutter dart


【解决方案1】:

这个问题是重复的,但我现在使用了一个我觉得值得分享的解决方案。

您可以使用扩展将函数放在 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 中进行测试。

【讨论】:

  • 你应该小心使用 .utc ,否则你可能会越过 DST 边界,这会打乱比较。
猜你喜欢
  • 2022-11-23
  • 2023-03-19
  • 2021-07-12
  • 1970-01-01
  • 2012-02-24
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
相关资源
最近更新 更多