繁体   English   中英

Flutter/Dart - 在输入表单中格式化日期

[英]Flutter/Dart - Format Date in input form

如何格式化日期并从以下位置更改:

电流输出

只是 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());
      });
  }

您可以使用intl packageDateFormat class 。 您必须在 pubspec.yaml 中添加intl: ^0.16.1作为依赖pubspec.yaml 最新版本可以在这里找到。

您可以指定希望日期输出的确切格式。

前任。

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
      });
  }
    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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM