代码之家  ›  专栏  ›  技术社区  ›  Toujo

如何使用DateTimePicker格式化日期时间并将所选日期作为字符串?

  •  1
  • Toujo  · 技术社区  · 2 年前

    我试着用这个=> choosenFromCalender = DateFormat('dd-MM-yyyy').format(newValue);

    但此错误的无法正确格式化。

    enter image description here

      DateTimePicker(
                               
                                dateMask: 'dd-MM-yyyy',
                                initialValue: DateTime.now().toString(),
                                type: DateTimePickerType.date,
                                firstDate: DateTime(1800),
                                lastDate: DateTime(2050),                                
                                onChanged: (newValue) {
                                  print(newValue);  // for now its `2022-07-27` i want `27-07-2022`
                                
                                },
    
                                onSaved: (value) {
    
                                },
                              ),
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   Sagar Patel    2 年前

    你需要格式化选择的日期

    为此,您需要在onChanged方法中输入以下代码

    newValue=DateFormat('dd-MM-yyyy').format(DateTime.parse(newValue);
    
        2
  •  1
  •   Tempelritter    2 年前

    问题是你从 newValue 返回字符串,但DateFormat只能处理DateTime格式。您可以做的是,将字符串解析为DateTime对象。

    DateTime dt = DateTime.parse(newValue);
    

    这个 dt 对象,然后可以使用该对象设置日期时间的格式。

    但还有更好的选择。您可以同时执行这两个操作。

     print(DateFormat('dd-MM-YYYY').parse(newValue));
    

    根据需要使用onChanged方法中的值打印格式化日期