【问题标题】:Flutter/Dart - Format Date in input formFlutter/Dart - 在输入表单中格式化日期
【发布时间】: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());
      });
  }

【问题讨论】:

标签: date flutter datetime dart


【解决方案1】:

您可以使用intl packageDateFormat 类。您必须在 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);
    

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 2019-03-13
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 2013-04-14
      • 2015-09-02
      相关资源
      最近更新 更多