Flutter/Dart - 在输入表单中格式化日期
Posted
技术标签:
【中文标题】Flutter/Dart - 在输入表单中格式化日期【英文标题】:Flutter/Dart - Format Date in input form 【发布时间】:2020-11-30 09:37:29 【问题描述】:我如何格式化日期并更改自:
只是 dd/mm/yyyy?
输入域代码:
textFields.add(
GestureDetector(
onTap: () => _selectDate(context),
child: AbsorbPointer(
child: TextFormField(
style: TextStyle(
fontSize: 12.0
),
controller: _date,
keyboardType: TextInputType.datetime,
decoration: InputDecoration(
isDense: true,
fillColor: Colors.white,
hintText: 'Date of Birth',
filled: true,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(width: 0.0),
),
contentPadding: const EdgeInsets.only(left: 14.0, bottom: 10.0, top: 10.0),
),
onSaved: (value) => _dateOfBirth = value,
),
),
));
_selectDate 方法:
DateTime selectedDate = DateTime.now();
TextEditingController _date = new TextEditingController();
Future<Null> _selectDate(BuildContext context) async
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
lastDate: DateTime(2100));
if (picked != null && picked != selectedDate)
setState(()
selectedDate = picked;
_date.value = TextEditingValue(text: picked.toString());
);
【问题讨论】:
关注这个答案:***.com/questions/51579546/… 【参考方案1】:您可以使用intl package 的DateFormat
类。您必须在 pubspec.yaml
中添加 intl: ^0.16.1
作为依赖项。最新版本可以在here找到。
您可以指定希望输出日期的确切格式。
例如
import 'package:intl/intl.dart';//Import intl in the file this is being done
Future<Null> _selectDate(BuildContext context) async
DateFormat formatter = DateFormat('dd/MM/yyyy');//specifies day/month/year format
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
lastDate: DateTime(2100));
if (picked != null && picked != selectedDate)
setState(()
selectedDate = picked;
_date.value = TextEditingValue(text: formatter.format(picked));//Use formatter to format selected date and assign to text field
);
【讨论】:
【参考方案2】: DateTime now = DateTime.now(); //current date
DateFormat formatter = DateFormat('yyyy-MM-dd'); // use any format
String formatted = formatter.format(now);
print(formatted); // something like 2013-04-20
如果你有日期选择器而不是
DateFormat formatter = DateFormat('yyyy-MM-dd'); // use any formate
String formatted = formatter.format(picked);
【讨论】:
以上是关于Flutter/Dart - 在输入表单中格式化日期的主要内容,如果未能解决你的问题,请参考以下文章
如何防止 Visual Studio Code Flutter/Dart Editor 格式化新行/换行代码?
如何将 TextButton 背景颜色输入到 Flutter/dart 中的函数