'How to calculate age using datetimepicker?
Im trying to figuring out how to calculate the age of user in my flutter application. What I want is only valide user which are have a min age of 18. Heres my code
String _date = "Please pick Age";
Widget _buildage() {
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
'Enter Age',
style: kLabelStyle,
),
SizedBox(height: 10.0),
Container(
decoration: kBoxDecorationStyle,
alignment: Alignment.centerLeft,
height: 70.0,
child: Container(
child: TextFormField(
initialValue: "haaas",
validator: (val) {
if (val.isEmpty) {
return 'Enter yout Age';
}
if (val.length < 4) {
return 'Enter a username minimun 4 chars long';
}
return null;
},
onChanged: (val) {
setState(() => age = val);
},
onTap: () {
DatePicker.showDatePicker(context,
theme: DatePickerTheme(
containerHeight: 210.0,
),
showTitleActions: true,
minTime: DateTime(2000, 1, 1),
maxTime: DateTime(2022, 12, 31), onConfirm: (date) {
setState(() {
_date = '${date.year} - ${date.month} - ${date.day}';
});
}, currentTime: DateTime.now(), locale: LocaleType.en);
},
readOnly: true,
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.date_range_rounded,
color: Colors.white,
size: 28,
),
hintText: " $_date",
hintStyle: kHintTextStyle,
),
),
),
),
]);
}
So in the TextformField I wanna check also if user has a minimum age of 18.Hope anyone can help. If you need more information please leave a comment .
Solution 1:[1]
//the selected date
var userSelectedDate = DateTime(1999, 12, 26);
//the duration difference form the selected date to now in days
var days = DateTime.now().difference(userSelectedDate).inDays;
//the duration difference in years (the current age)
var age = days ~/ 360;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mohammed Alfateh |